3 minutes learn to choose the sort

Ideas: Selection Sort is the time to choose the smallest element to add to the end of the ordered area

  1. Ordered regions to be divided discharge area, a length of zero ordered regions start
  2. To be found in the discharge area smallest element, and orderly exchange zone + 1 position, comparing the end of the trip. A total of n-1 times required
  3. By sequentially comparing the area element to be ranked and choose the smallest element
  4. Time complexity of O (n ^ 2), preferably with the worst case, in order to find the smallest element, the inner cycle need to be performed

public class Solution {
    public static void selectSort(int[] array) {
        int minIndex;
        int temp;
        for (int i = 0; i < array.length - 1; i++) {
            minIndex = i;
            for (int j = i + 1; j < array.length; j++) {
                if (array[j] < array[minIndex]) {
                    minIndex = j;
                }
            }
            if (minIndex != i) {
                temp = array[i];
                array[i] = array[minIndex];
                array[minIndex] = temp;
            }
        }
    }

    public static void main(String[] args) {
        int[] array = new int[]{2, 5, 1, 6, 9, 3};
        selectSort(array);
        for (int i : array) {
            System.out.print(i + " ");
        }
    }
}

 

Published 244 original articles · won praise 16 · views 50000 +

Guess you like

Origin blog.csdn.net/qq_29150765/article/details/105187123