4 Java Selection Sort

 

1 The basic idea

Finding the minimum element in the unsorted sequence, stored in the start position of unsorted sequence. In all entirely dependent on the switching element to move the sorting method, select an algorithm to sort belonging to very good, need to compare len-n-1 times, but only the exchange of views 0 or 1.

Algorithm description

. ① to be sorted from the column, find the smallest element;

. ② if the smallest element of the first column is not to be sorted, which is the first element and interchangeable;

③ from the remaining N -. 1 element, find the smallest element, is repeated ①, ② step, until the end of the sort.

 

3, code implementation:

public class ChoiceSort {

    public static void main(String[] args) {
        int[] array = new int[]{10, 1, 9, 2, 8, 3, 7, 4, 6, 5};
        choiceSort(array);
    }

    /**
     * Example:
     * 10, 1, 9, 2, 8, 3, 7, 4, 6, 5
     * 1, 10, 9, 2, 8, 3, 7, 4, 6, 5
     * 1, 2, 9, 10, 8, 3, 7, 4, 6, 5
     * 1, 2, 3, 10, 8, 9, 7, 4, 6, 5
     * @param array
     */
    public static void choiceSort(int[] array) {
        int len = array.length;
        for (int i=0; i<len-1; i++) {
            int minIndex = i;
            for (int j=i; j<len-1; j++) {
                // 将最小元素下标赋给minIndex
                if (array[minIndex] > array[j+1]) {
                    minIndex = j + 1 ;
                }
            }
            // minimum unsorted not the first element of the sequence, to exchange the 
            IF (minIndex! = I) {
                SortUtil.swap (array, minIndex, i);
            }
            System.out.println(Arrays.toString(array));
        }
    }
}
View Code

 

Guess you like

Origin www.cnblogs.com/Latiny/p/10519783.html