希尔排序

//*****************************希尔排序****************************
//思路:把数据分为几组,每组有gap个数据,gap可以是固定的,也可根据
//      数组的大小来变动,做法和插入排序一样,只是每次数据后移时要后移
//      gap个位置,end--的时候也要移动gap个位置
//NOTE:end+gap不能超过数组的最大下标,否则会取到随机数
//      while (end >= 0 && a[end]>tmp && end + gap < size)
//      或者在for循环里面控制for (int index = 0; index < size - gap; ++index)
void ShellSort( int * a , size_t size )
{
                 assert ( a );
                 int gap = size ;
                 while (gap > 1)
                {
                                gap = gap / 3 + 1;
                                 for ( int index = 0; index < size ; index++)
                                {
                                                 int end = index;
                                                 int tmp = a [end + gap];
                                                 while (end >= 0 && a [end]>tmp /* && end + gap < size*/ )
                                                {
                                                                 a [end + gap] = a [end];
                                                                end -= gap;;
                                                }
                                                 a [end + gap] = tmp;
                                }
                }
}

void ShellSortTest()
{
                 //int arr[] = { 9, 5, 4, 2, 3, 6, 8, 0, 1, 7 };
                 int arr[] = { 9, 5, 4, 2, 5, 6, 8, 5, 1, 7 };
                 int _size = sizeof (arr) / sizeof (arr[0]);
                ShellSort(arr, _size);
                Print(arr, _size);
}

你可能感兴趣的:(希尔排序)