[Data Structure and Algorithm] Selection Sort

Selection sort:
time complexity: O (n ^ 2)
space complexity: O (1)

Performance test:
Compared with bubble sorting:

Sort by 10k random numbers:

选择排序        :       0.109496 s
冒泡排序优化版  :       0.432141 s

10k nearly ordered numbers sort:

选择排序        :       0.112428 s
冒泡排序优化版  :       0.018859 s

Basic idea:
select the smallest one from the interval to be sorted and place it after the already ordered interval.

void selectSort(int arr[], int n) {
    for (int i = 0; i < n; ++i) {

        int min_index = i;
        for (int j = i + 1; j < n; ++j) {
            if (arr[j] < arr[min_index]) {
                min_index = j;
            }
        }

        swap(arr[i], arr[min_index]);
    }
}

EOF

98 original articles have been published · 91 praises · 40,000+ views

Guess you like

Origin blog.csdn.net/Hanoi_ahoj/article/details/105473481