Ideas
Selective sorting is similar to the bubble sorting and insertion sorting routines mentioned earlier . They both divide the array into sorted and unsorted sub-arrays. The main difference lies in element selection and placement . Selection Sort from unsorted selected array minimum (or maximum) is placed in a sorted array after.
The following uses | to separate sorted and unsorted arrays, such as:
data to be sorted: 7, 0, 2, 8, 1 (the ordered array is empty at the beginning)
Sorting once :
0 | 7, 2, 8, 1 (put the smallest number 0 after the ordered array ())
Secondary sorting :
0, 1 | 7, 2, 8 (put the smallest number 1 into the ordered array (0))
Sort three times :
0, 1, 2 | 7, 8 (put the smallest number 2 into the ordered array (0, 1))
Four sorting :
0, 1, 2, 7 | 8 (put the smallest number 7 into the ordered array (0, 1, 2))
Five sorts :
0, 1, 2, 7, 8 (put the smallest number 8 into the ordered array ( 0, 1, 2, 7 ))
The time complexity of the selection sorting algorithm is O(n^2)
Implementation code:
void selectSorted(vector<int>& nums) {
int len = nums.size();
int index, temp;
for (int i = 0; i < len; i++) {
index = len - 1;
for (int j = len - 2; j >= i; j--) {
// 从i~len-1中获取最小元素的索引
if (nums[index] > nums[j]) {
//这里是升序排序,若是要降序 把 '>' 改成 '<' 即可
index = j;
}
}
// 通过交换的方式,将未排序的最小值,放入已排序数组(0~i-1)最后
temp = nums[index];
nums[index] = nums[i];
nums[i] = temp;
}
}
end
If you want to know about other sorts, click here: Summary of Sorting Algorithms