Learn Computer Science programming - C# and C++ Algorithms

 
Shell Sort

This is the most efficient of the O(n2) class of sorting algorithms. It is also the most complex amoung them. Known as the comb sort, it makes multiple passes through the list, and each time sorts a number of equally sized sets using the insertion sort. The size of the set to be sorted gets larger with each pass through the list, until the set consists of the entire list. It is efficient for medium size lists, but somewhat compelx. It is also not nearly as efficient as the merge, heap, and quick sorts. 
Code
c_shell_sort.zip
File Size: 23 kb
File Type: zip
Download File

using System;
using System.Collections;

namespace Sort
{
    public class SortShell
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            int[] numbers = new int[] { 3, 4, 65, 7, 8, 11, 2234, 4, 117 };
            int i, j, tmp, n;

            n = numbers.Length;
            Console.WriteLine("Before");
            Display(numbers);
            shellSort(numbers, n);
            Console.WriteLine("\r\nAfter");
            Display(numbers);
        }

        static void shellSort(int[] numbers, int array_size)
        {
            int i, j, increment, temp;
            increment = 3;
            while (increment > 0)
            {
                for (i = 0; i < array_size; i++)
                {
                    j = i;
                    temp = numbers[i];
                    while ((j >= increment) && (numbers[j - increment] > temp))
                    {
                        numbers[j] = numbers[j - increment];
                        j = j - increment;
                    }
                    numbers[j] = temp;
                }
                if (increment / 2 != 0)
                    increment = increment / 2;
                else if (increment == 1)
                    increment = 0;
                else
                    increment = 1;
            }
        }

        static void Display(int[] numbers)
        {
            //Display Array Content
            IEnumerator sorted = numbers.GetEnumerator();
            while (sorted.MoveNext())
            {
                Console.WriteLine(sorted.Current);
            }
        }
    }
}