Sort learning algorithm [2] Selection Sort

3. Select Sort

Selection Sort (Selection sort) is a straightforward sorting algorithm. Its working principle is: the first data element to be sorted from the selected minimum (or maximum) of an element stored in the starting position of the sequence, and then to find from the remaining unsorted elements to a minimum (large) elements, and then into the end of the sequence sorted. And so on, until all the number of data elements to be sorted is zero. Select sort is unstable sorting method.

Principle of the moving map presentation

Code

/*选择排序*/
int selectSort(int *arr, int length) {
    // 统计比较次数
    int count = 0;
    for (int i = 0; i < length; i++) {
        int index = i;
        for (int j = index + 1; j < length; j++) {
            if (arr[index] > arr[j])
            {
                index = j;
            }
            count++;
        }
        int temp = arr[i];
        arr[i] = arr[index];
        arr[index] = temp;
    }
    return count;
}

operation result

First, the outer loop in the definition of the value of a variable to store index i, which is to avoid duplication compare, because at the end of each round of comparison, before the i-th element is already sorted, so no comparison again, just i can from the start. Later comparisons are performed based on the element index position comparison, if the index position of the element after the comparison is the minimum, without exchanging it, you can not move. If the element is smaller than the index position of the element is found, then the index of the element assigned to the index, then the comparison continues until the completion of the comparison, the minimum value of the array index that is obtained after completion of the comparison is that at this time simply position the elements element and i want to exchange index position.

Reference Hirofumi

[1] Those programmers sorting algorithm (on) must be mastered https://blog.csdn.net/qq_42453117/article/details/99680831
[2] three simple sorting (bubble, insertion, selection) and graphical comparison https://blog.csdn.net/cc1258000/article/details/79113211

Guess you like

Origin www.cnblogs.com/hellovan/p/11410640.html