Hill sorting is the optimization of direct insertion sorting. Both the number of comparisons and the number of inserts should decrease.
# Include <stdio. h> # include <stdlib. h> void swap (int arr [], int I, int j) {int temp; temp = arr [I]; arr [I] = arr [j]; arr [j] = temp;} void ShellSort (int arr [], int n) {int I; int increment = n/2; while (increment! = 0) {for (I = increment; I <n; I ++) // The loop starts from the first 2nd array elements, shift arr [0] as the first sorted part {int j; int temp = arr [I]; for (j = I-increment; j> = 0 & arr [j]> temp; j = j-increment) arr [j + increment] = arr [j]; arr [j + increment] = temp;} increment = increment/2;} void print (int arr [], int n) {int I; for (I = 0; I <n; I ++) {printf ("% d", arr [I]);} printf ("\ n");} int main () {int arr [] = {9, 1, 5, 8, 3, 7, 4, 6, 2}; int n = sizeof (arr) /sizeof (arr [0]); printf ("Before sorting: \ n"); print (arr, n); ShellSort (arr, n); printf ("after sorting: \ n "); print (arr, n); system (" pause "); return 0 ;}
This article is from "Li Haichuan" blog, please be sure to keep this source http://lihaichuan.blog.51cto.com/498079/1282211