希爾排序

1, 希爾排序是一種O(N^1.25)(公認的,沒有數學證明),好於O(N*N)。

2, 希爾排序可以說就是插入排序的增量模式,最小增量必須有1。也可以理解爲對數列的多次分組插入排序。分組間隔爲1的情況,就是插入排序。所以希爾排序的分組間隔的選擇關係到排序算法的優劣。

3, 希爾排序是一種不穩定的排序算法。

 

#include "stdafx.h"
#include "stdio.h"

void InsertSort(int* data, int length, int step)
{
 for( int i = step; i < length; i++ )
 {
  int temp = *(data+i);
  for( int j = i; j > 0; j -= step )
  {
   if( *(data+j-step) > temp )
    *(data+j) = *(data+j-step);
   else
    break;
  }
  *(data+j) = temp;
 }
}

//void ShellSort(int A[], int count)
//{
// int i, j, increment;
// int temp;
//
// for( increment = count / 2; increment > 0; increment /= 2 )
// {
//  for( i = increment; i < count; i++ )
//  {
//   temp = A[i];
//   for( j = i; j >= increment; j -= increment )
//   {
//    if( A[j-increment] > temp )
//     A[j] = A[j-increment];
//    else
//     break;
//   }
//   A[j] = temp;
//  }
// }
//}

void ShellSort(int A[], int count)
{
 int i, j, increment;
 int temp;

 for( increment = count / 2; increment > 0; increment /= 2 )
 {
  InsertSort(A, count, increment);
 }
}

int _tmain(int argc, _TCHAR* argv[])
{
 int A[] = {34, 8, 64, 51, 32, 21};
 int count = sizeof(A) / sizeof(A[0]);

 //for( int i = 1; i < count; i++ )
 //{
 // int temp = A[i];
 // for( int j = i; j > 0; j-- )
 // {
 //  if( temp < A[j-1] )
 //   A[j] = A[j-1];
 //  else
 //   break;
 // }
 // A[j] = temp;
 //}

 //InsertSort(A, count, 1);

 ShellSort(A, count);

 for( int i = 0; i < count; i++ )
  printf("%d  ", A[i]);

 return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章