ShellSort | C # implementation of ShellSort ; An utility function to print array of size n ; function to sort arr using shellSort ; Start with a big gap , then reduce the gap ; Do a gapped insertion sort for this gap size . The first gap elements a [ 0. . gap - 1 ] are already in gapped order keep adding one more element until the entire array is gap sorted ; add a [ i ] to the elements that have been gap sorted save a [ i ] in temp and make a hole at position i ; shift earlier gap - sorted elements up until the correct location for a [ i ] is found ; put temp ( the original a [ i ] ) in its correct location ; Driver method
using System ; class ShellSort { static void printArray ( int [ ] arr ) { int n = arr . Length ; for ( int i = 0 ; i < n ; ++ i ) Console . Write ( arr [ i ] + " ▁ " ) ; Console . WriteLine ( ) ; } int sort ( int [ ] arr ) { int n = arr . Length ; for ( int gap = n / 2 ; gap > 0 ; gap /= 2 ) { for ( int i = gap ; i < n ; i += 1 ) { int temp = arr [ i ] ; int j ; for ( j = i ; j >= gap && arr [ j - gap ] > temp ; j -= gap ) arr [ j ] = arr [ j - gap ] ; arr [ j ] = temp ; } } return 0 ; } public static void Main ( ) { int [ ] arr = { 12 , 34 , 54 , 2 , 3 } ; Console . Write ( " Array ▁ before ▁ sorting ▁ : STRNEWLINE " ) ; printArray ( arr ) ; ShellSort ob = new ShellSort ( ) ; ob . sort ( arr ) ; Console . Write ( " Array ▁ after ▁ sorting ▁ : STRNEWLINE " ) ; printArray ( arr ) ; } }