Data structure sorting-hill sort

Source: Internet
Author: User
Tags sorts

The hill sort is also one of the insertion sorts, but it is more efficient than the direct insertion sort.

The basic idea is:

First, take an integer less than n D1 as the first increment, grouping all the records in the file. All records with a multiple of D1 are placed in the same group. First, the direct insertion in each group is sorted;

Then, take the second increment d2< to repeat the above groupings and sorts until the increment dt=1 is taken.

The incremental sequence is particularly critical, with half of the general first-time sequence being incremented, and halving it later, until the increment is 1.

1#include <stdio.h>2#include <stdlib.h>3 4 intN;5 6 /*7 * Hill Sort8  */9 voidShellsort (int*Array)Ten { One     intK = n/2;//incremental sequence (for example only) A      while(k >0) -     { -         intI, J; the          for(i = k +1; I <=n; i++) -         { -             if(Array[i] < array[i-K]) -             { +array[0] =Array[i]; -                  for(j = i-k; J >0&& array[0] < ARRAY[J]; J-=k) +                 { AArray[j + K] =Array[j]; at                 } -Array[j + K] = array[0]; -             } -         } -K = k/2; -     } in } -  to intMain () + { -     inti; the     int*Array; *printf"Please enter the size of the array:"); $scanf"%d", &n);Panax NotoginsengArray = (int*)malloc(sizeof(int) * (n +1)); -printf"Please enter data (separated by spaces):"); the      for(i =1; I <= N; i++) +     { Ascanf"%d", &array[i]); the     } + Shellsort (array); -printf"after sorting is:"); $      for(i =1; I <= N; i++) $     { -printf"%d", Array[i]); -     } theprintf"\ n"); -}

The direct insert sort is stable, the worst time complexity is O (n^2), and the spatial complexity is O (1).

The hill sort is unstable, the time complexity is related to the increment sequence, and the increment sequence is taken to ensure that the value is not a common factor other than 1, and that the last increment must be 1.

Data structure sorting-hill sort

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.