Algorithms (b) Selection Sort

Sort principle

The so-called selection sort is to find the minimum value from a given unsorted array element in turn, and the minimum order is already sorted on the elements behind until all drained. For the sorting process, first find the minimum value of the array index, and the first element in the array and the minimum switching position, then find a minimum index remaining unsorted element, and a second array switching elements and a minimum position, and then repeat the above steps until all elements of the sort is complete.
Here Insert Picture Description

time complexity

  • Whether array is a positive sequence or in reverse order, as when the i-th traversal, the need for ni comparisons, all sort down requires n * (n-1) / 2 comparisons, but also need to exchange element positions, the total number of mobile is 3n * (n-1) / 2 times, the time complexity is O (n2).

Sort Code

public class SelectionSort {

    /**
     * 选择排序
     */
    public void selectionSort(int[] arr, int a, int n) {
        //寻找数组中[a,n)区间的最小值
        for (int i = a; i < n; i++) {
            //定义一个最小值的下标
            int min = i;
            for (int j = i + 1; j < n; j++) {
                //利用第一个数与其余的比较找出最小值的下标
                if (arr[min] > arr[j]) {
                    min = j;
                }
            }
            //如果最小下标不等于当前元素,那么就说明找到了最小元素
            if (min != i) {
                int temp = arr[i];
                arr[i] = arr[min];
                arr[min] = temp;
            }
        }
    }
}
Published 94 original articles · won praise 55 · views 110 000 +

Guess you like

Origin blog.csdn.net/Suubyy/article/details/100039752