Tuesday 12 August 2014

Shell Sort in C#

Shell Sort:
It improves upon Bubble Sort and Insertion Sort by moving out of order elements more than one position at a time. It compares elements separated by a gap of several positions. This lets an element take "bigger steps" toward its expected position. Multiple passes over the data are taken with smaller and smaller gap sizes. The last step of Shell Sort is a plain Insertion Sort, but by then, the array of data is guaranteed to be almost sorted.


using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace DataStructureAlgoriths
{
    class Sort
    {
public void ShellSort()
        {
            long[] inputArray = new long[] { 4, 9, 8, 6, 3, 2, 1 };
            long j, temp = 0;
            int increment = (inputArray.Length) / 2;
            while (increment > 0)
            {
                for (int index = 0; index < inputArray.Length; index++)
                {
                    j = index;
                    temp = inputArray[index];
                    while ((j >= increment) && inputArray[j - increment] > temp)
                    {
                        inputArray[j] = inputArray[j - increment];
                        j = j - increment;
                    }
                    inputArray[j] = temp;
                }
                if (increment / 2 != 0)
                    increment = increment / 2;
                else if (increment == 1)
                    increment = 0;
                else
                    increment = 1;
            }
            foreach (var item in inputArray)
            {
                Console.WriteLine(item);
            }
        }
}
}

using System;
using System.Collections.Generic;
using System.Text;

namespace DataStructureAlgoriths
{
    class Program
    {
        static void Main(string[] args)
        {
            Sort s = new Sort();
            s.ShellSort ();
            Console.ReadLine();
        }
    }

}


No comments:

Post a Comment