Java - Selection Sort Algorithm

后端 未结 17 1646
我在风中等你
我在风中等你 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

    Assume a lowest element, which requires scanning the all elements and then swap it to the first position.

    private static void selectionSortMethod(int[] arr) {
    
            for (int i = 0; i < arr.length - 1; i++) {  //no of iterations for array length
                for (int j = i + 1; j < arr.length; j++) {  //starting from next index to lowest element(assuming 1st index as lowest)
                    if (arr[i] > arr[j]){
                        int temp = arr[i];
                        arr[i] = arr[j];
                        arr[j] = temp;
                    }
                }
    
            }
             //print 
            for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i]+" ");
            }
        }
    

提交回复
热议问题