虽然代码不多,但是逻辑性很强
一:shell排序,代码如下:
/*
用到的增量系列 h = h*3 + 1, 所以逆系列为 h = (h-1)/3;
*/
#include <iostream>
using namespace std;
void m_shellSort(int* arr, int nLen){
int h = 1;
// 得到系列最大值
while(h <= nLen/3){
h = h*3 + 1;
}
while(h > 0){
// 这个循环很有内涵,一个h值会把这个数组分成几个不相干的系列
// 比如:h=4 {0, 4, 8 ···}, {1, 5, 9···}···我们
// 的策略是把所有系列一起从头到尾处理
for(int i = h; i < nLen; i++){
int tmp = arr[i];
if(tmp < arr[i-h]){
int j = i-h;
for( ; arr[j] > tmp && j >= 0; j -= h){
arr[j+h] = arr[j];
}
arr[j+h] = tmp;
}
}
h = (h-1)/3;
}
}
int main(int argc, char* argv[])
{
int testArr[] = {23, 45, 1, 2, 77, 6, 54, 108, 289, 3, 0, 2, 77};
int len = sizeof(testArr)/sizeof(int);
m_shellSort(testArr, len);
for(int i = 0; i < len; i++){
cout << testArr[i] << " ";
}
cout << endl;
return 0;
}
记下来方便以后查看