Sort(Ⅰ)

  1. Select :
    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<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
	}
}
  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<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!

  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<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!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值