Java - Selection Sort Algorithm

后端 未结 17 1620
我在风中等你
我在风中等你 2020-12-17 04:26

I have some questions about selection sort.I\'m a little bit confused.

 int [] arr = {5,4,3,2,1}; // This is my array
    int min = 0;

    for(int i = 0;i&l         


        
17条回答
  •  执念已碎
    2020-12-17 04:48

    public class SelectionSort {
    
    public static void main(String[] args) {
        int[] A = {5,4,3,2,1};
        int l = A.length;
    
        for (int i = 0; i < l-1; ++i ){
            int minPos = i;
    
            // Find the location of the minimal element
            for (int j = i + 1; j < l; ++j){
                if ( A[j] < A[minPos]){
                    minPos = j;
                }
            }
    
            if (minPos != i){
                int temp = A[i];
                A[i] = A[minPos];   
                A[minPos] = temp;
            }
        }
        System.out.println(Arrays.toString(A));
    }
    }
    

提交回复
热议问题