Shell Sort Algorithm in C# (Insertion with middle position split)

class ShellSort
    {

        public static List<int> Execute(List<int> list)
        {
            //Start position is at the middle of the list.
            var position = list.Count / 2;

            //Iterate as long as we don't reach the "bottom"
            while (position > 0)
            {
                //Go through the entire list
                for (int i=0;i<list.Count;i++)
                {
                    //Get current index
                    var index = i;

                    //Get current item
                    var current = list[i];


                    while (index >= position &&                 //As long as we have not reached this position AND
                           list[index - position] > current)    //Item at a more previous index greater than current
                    {
                        //Swap (travel more than one position)
                        list[index] = list[index - position];

                        //Go back (more than one position)
                        index -= position;
                    }
                }

                if (position / 2 != 0)
                {
                    //Travel back another half
                    position = position / 2;
                }
                else if (position == 1)
                {
                    //No need to go more
                    position = 0;
                }
                else
                {
                    position = 1;
                }
            }

            return list;
        }

    }

Comments

Popular posts from this blog

Tutorial: Using Google Cloud Storage from C# and .NET

Late 2008 Macbook only giving 1.5 gb/s speed with 6 gb/s Intel SSD?

The ridiculous interview experience