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