1. 程式人生 > >希爾排序(shell sort)

希爾排序(shell sort)

#include <stdio.h>
#include <stdlib.h>

int shell_sort(int num_array[], int num)
{
     int i, j, temp; 
     int gap = 0;

     while (gap<=num)
     {
          gap = gap * 3 + 1;
     } 
     
     while (gap > 0) 
     {
         for ( i = gap; i < num; i++ )
         {
             j = i - gap;
             temp = num_array[i];             
             while (( j >= 0 ) && ( num_array[j] > temp ))
             {
                 num_array[j + gap] = num_array[j];
                 j = j - gap;
             }
             num_array[j + gap] = temp;
         }
         gap = ( gap - 1 ) / 3;
     }    
     return 0;
 }

void main() 
{
    int i;
    int num_array[20];

    srand(0);
    printf("\r\n init: ");
    for(i = 0; i < 20; i++) {
        num_array[i] = rand()%1000;
        printf("%d ", num_array[i]);
    }

    shell_sort(num_array, 20);
    printf("\r\n shell sort: ");
    for(i = 0; i < 20; i++) {
        printf("%d ", num_array[i]);
    }
}