Hill sort algorithm code

  • 2020-04-01 01:27:23
  • OfStack

The time complexity of hill sort is O (n * log2n) and the space complexity is O (1), which is an unstable sorting algorithm

Idea: hill sort is also an insertion sort method, actually a grouping insertion method. Firstly, d1, an integer less than n, is selected as the first increment, and all records of the table are divided into d1 groups. All records with distance multiples of d1 are put into the same group, and direct insertion sort is conducted in each group. Then, take the second increment, d2(< d1), and repeat the above grouping and sorting until the increment, dt=1(dt< Dt - 1 < ... < D2 < D1), that is, until all records are placed in the same group for direct insertion sort.      


void ShellSort(int* data ,int length)
{
    if( data == NULL || length <= 0 )
        return;
    int d = length/2;  //Step length
    while( d )
    {
        for(int i = 0 ; i < d ; ++i) // According to the Step length Divide into groups and work on each group Insertion sort
        {
            //Insertion sort
            for(int j = i+d; j <length ; j +=d )
            {
                if( data[j] < data[j -d]) 
                {
                    int temp = data[j]; //The sentry
                    int k = j-d;
                    for(; k >=0&& temp < data[k]; k -=d)
                    {
                        data[k+d] =data[k];
                    }
                    data[k+d] =temp;
                }
            }
        }
        d = d/2;
    }
}


Related articles: