-
Select :
thinking:
(1) First, get the current one.
(2) Then find the smallest one in the suffix array, exchange it with the current oneevaluate:
(1) Input unrelated:
The time required is not related to the input (ironically, you will find it stupid when the array is even sorted!
(2)Remove least:
remove N elements in total. (this is the unique characteristic!)
template<class T>
void selectSort(T a[], int n) {
for (int i = 0; i < n - 1; i++) {
int min = i; //get the current one
for (int j = i + 1; j < n; j++) { //find the smallest one
if (a[j] < a[min])
min = j;
}
swap(a[min], a[i]); //exchange them
}
}
- insertSort:
thinking:
(1) insert a[i] between a[i-1], a[i-2], … thus we should move the prefix array to make enough room for the new one.
(2) As for the current element, compare it with the prefix elements — while it is bigger than them, stop.
template<class T>
void insertSort(T a[], int n) {
for (int i = 1; i < n; i++) {
for (int j = i; j > 0 && a[j] < a[j - 1]; j--) {
swap(a[j], a[j - 1]);
}
}
}
evaluate:
especially suitable for the Non-random arrays — in this case, it might be the best sort algorithm!
- shellSort:
thinking:
(1) based on the insertSort, optimize it with a gap (not 1);
(2) make any 2 elements with a gap of h is sorted.
(3) So we need a increment sequence — normally we used 3X+1 sequence.
template<class T>
void shellSort(T a[], int n) {
int h = 1;
while (h < n / 3)
h = 3 * h + 1;
while (h) {
for (int i = h; i < n; i++) {
for (int j = i; j >= h && a[j] < a[j - h]; j -= h) {
swap(a[j], a[j - h]);
}
}
h /= 3;
}
}
evaluate:
It is fast enough, though— even the fastest algorithm are not twice as fast as it.
So if you really need to sort a set of elements that are middle size … you should utilize it!