shell排序是一种优化的插入排序算法,其思想是将待排序列分红若干组,而后对每组分别进行插入排序;而后不断减少分组增量到1,即完成排序过程。算法
具体看下面吧。shell
shell_sort.h函数
/************************************************************************/ /* 希尔排序又称“缩小增量排序”,是对直接插入排序算法的改进 */ /* 希尔排序的思想是,先将整个待排记录分红若干序列,而后分别进行直接插入排序*/ /*具体作法以下先取一个小于n的增量d1做为第一个增量,即将全部距离d1的元素分红一组*/ /*因而n分红以下d1组*/ /*0,d1,2*d1,3*d1.......k*d1 */ /*1,1+d1,1+2*d1.。。。。。*/ /*也就是begin,begin + d1 , 。。。。。begin + k * d1 < n , begin {0,d1-1}*/ /*经过屡次d排序,便可*/ /************************************************************************/ /* *a为待排序列,length为长度,increment_sector为增量因子,就是增量d如何取得 *实验结果increment_sector =3时,shell_sort时间复杂度最小及n的1.3次方 */ void shell_sort(int a[], int length, int increment_sector); /* *该函数是对插入排序的改进 *a为待排序列,length为长度,begin为组别第一个的下标,step为分组中两个元素下标距离也就是增量d */ void insert_sort_step(int a[],int length, int begin, int step);
shell_sort.cpp优化
#include "Shell_Sort.h" /* *a为待排序列,length为长度,increment_sector为增量因子,就是增量d如何取得 *实验结果increment_sector =3时,shell_sort时间复杂度最小及n的1.3次方 */ void shell_sort(int a[], int length, int increment_sector){ //须要屡次增量插入排序,直到增量为1,进行全排 for (int step = length / increment_sector; step > 0; step = step / increment_sector ) { //对每一个增量分组进行插入排序分组下标:begin + step * k < n; for (int begin = 0; begin < step; begin++) { insert_sort_step(a,length,begin,step); } } } /* *该函数是对插入排序的改进 *a为待排序列,length为长度,begin为组别第一个的下标,step为分组中两个元素下标距离也就是增量d *直接插入排序只需令begin = 0; step = 1; */ void insert_sort_step(int a[],int length, int begin, int step){ //执行插入排序 for (int i = begin + step; i < length; i = i + step) { int key = a[i]; //下面为元素i寻找合适的位置 for ( int j = begin; j < i; j += step) { if ( a[i] < a[j])//找到a[i]的位置,即为j,j以后的元素后移 { for( int k = i; k > j; k = k - step) { a[k] = a[k -step]; } a[j] = key; } } /* 关于插入排序有两种方式,一是上面那样从最前面向后查找,二是以下从后向前查找 */ /* int j = i - step; int key = a[j]; while(j > -1 && a[j] > key){ //此处为升序排列 a[j + step] = a[j]; //元素后移 j -= step; } a[j+step] = key; //找到位置,插入便可 */ } }