Shell Sort:
Shell sort is used to sort an array by iteratively placing the elements of that array into smaller sub-arrays and is followed by insertion sort. Counting on this idea, shell sort does not compare elements in the same way as the simple inserting sort does, but instead, it compares elements that are far from each other, not the ones near each other.
Below simple C# program shows how to do the shell sort easily.
using System;
class ShellSort {
public static void Sort(int[] array) {
int n = array.Length;
for (int gap = n / 2; gap > 0; gap /= 2) {
for (int i = gap; i < n; i += 1) {
int temp = array[i];
int j;
for (j = i; j >= gap && array[j - gap] > temp; j -= gap)
array[j] = array[j - gap];
array[j] = temp;
}
}
}
public static void PrintArray(int[] array) {
int n = array.Length;
for (int i = 0; i < n; i++)
Console.Write(array[i] + " ");
Console.WriteLine();
}
public static void Main(string[] args) {
int[] array = { 12, 34, 54, 2, 3 };
Console.WriteLine("Array before sorting:");
PrintArray(array);
Sort(array );
Console.WriteLine("Array after sorting:");
PrintArray(array);
}
}
Output:
Array before sorting:
12 34 54 2 3
Array after sorting:
2 3 12 34 54
Comments (0)