Java - Selection Sort Algorithm

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

    Selection sort is a sorting algorithm in which the smallest element is picked from an unsorted array and moved to the beginning of the array. In your case first find min value index from second for loop and swap outside on that loop.

    private static void selectionSort(int[] arr) {

            int n = arr.length;
            for (int i = 0; i < n - 1; i++) {
                int min = i;
                for (int j = i + 1; j < n; j++) {
                    if (arr[j] < arr[min]) {
                        min = j;
                    }
                }
                if (min != i) {
                    int temp = arr[i];
                    arr[i] = arr[min];
                    arr[min] = temp;
                }
            }
        }
    

提交回复
热议问题