Thursday, January 17, 2013

Recursive Merge Sort


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

        public int[] MergeSort(int[] input)
        {
            int[] temp = new int[input.Length];
            this.RecursiveMergeSort(input, temp, 0, (input.Length - 1) / 2, input.Length - 1);

            return input;
        }

        private void RecursiveMergeSort(int[] input, int[]temp, int low,int mid, int high)
        {
            if (low < high)
            {
                RecursiveMergeSort(input,temp,low, (low + mid) / 2, mid);
                RecursiveMergeSort(input, temp,mid + 1, (mid + 1 + high) / 2, high);
                Merge(input, temp, low, mid, high);

            }
        }

        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++];
                    }
                }
            }

        }

       
   
        static void Main(string[] args)
        {
            Random r = new Random(DateTime.Now.Millisecond);
            int arraySize = 10000000;
            int[] Merge= new int[arraySize];
           

            for (int x = 0; x < Quick.Length; x++)
            {
                Merge[x] = x;
            }

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


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

            StopWtch.Reset();
            StopWtch.Start();
            p.MergeSort(Merge);
            StopWtch.Stop();
            Console.WriteLine("MERGESORT:   " + StopWtch.Elapsed.TotalSeconds + "sec");
            Console.ReadLine();
        }
    }