Thursday, January 3, 2013

Iterative Merge Sort


class Program
    {
        private void Swap(int[] input, int x, int y)
        {
            var temp = input[x];
            input[x] = input[y];
            input[y] = temp;
        }

        private void Merge(int[] input, int[] temp, int low, int mid, int high)
        {
            for (int i = low; i <= high; i++)
            {
                temp[i] = input[i];
            }

            int l = low;
            int h = mid + 1 ;
            for (int i = low; i <= high; i++)
            {
                if (h > high)
                {
                    input[i] = temp[l++];
                }
                else if (l > mid)
                {
                    input[i] = temp[h++];
                }
                else
                {
                    if (temp[l] <= temp[h])
                    {
                        input[i] = temp[l++];

                    }
                    else
                    {
                        input[i] = temp[h++];

                    }
                }
            }
        }

        public int[] InlineMerge(int[] input)
        {
            temp = new int[input.Length];
            // i length of the merging arrays
            for (int i = 1; i < input.Length; i *= 2)
            {
                // j is the starting position of the current merging arrays
                for (int j = 0; j < input.Length; j += 2 * i)
                {
                    if (j + i < input.Length)
                    {
                        int high = j + 2 * i - 1<input.Length?j + 2 * i - 1:input.Length-1;
                        Merge(input, temp, j, j + i - 1,high);
                    }
                }
            }
            return input;
        }

   
        static void Main(string[] args)
        {
            Random r = new Random(DateTime.Now.Millisecond);
            int arraySize = 10000000;
            int[] IteMerge = new int[arraySize];
           
            for (int x = 0; x < IteMerge.Length; x++)
            {
                IteMerge[x] = x;
            }

            for (int x = 0; x < IteMerge.Length; x++)
            {
                int random = r.Next(0, x);
                var temp = IteMerge[random];
                IteMerge[random] = IteMerge[x];
                IteMerge[x] = temp;
            }


            var p = new Program();
            var StopWtch = new System.Diagnostics.Stopwatch();

            StopWtch.Reset();
            StopWtch.Start();
            p.InlineMerge(InlineMerge);
            StopWtch.Stop();
            Console.WriteLine("ITERATIVEMERGE: " + StopWtch.Elapsed.TotalSeconds + "sec");

            Console.ReadLine();
        }
    }