Sort(Ⅰ)

  1. selectSort :
    thinking:
    (1) First, get the current one.
    (2) Then find the smallest one in the suffix array, exchange it with the current one

    evaluate:
    (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
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
	}
}
  1. 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
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--) { // always exchange until the subarray is sorted.
			swap(a[j], a[j - 1]);
		}
	}
}

evaluate:
especially suitable for the Non-random arrays — in this case, it might be the best sort algorithm!

  1. 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
void shellSort(T a[], int n) {
	int h = 1;
	while (h < n / 3)
		h = 3 * h + 1;      // ask 3n+1 sequence for help
	while (h) {             // exchange all 2 elements with gap 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;            //find the next h
	}
}

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!

你可能感兴趣的:(总结笔记)