Advertisement
Guest User

Untitled

a guest
Dec 18th, 2013
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.82 KB | None | 0 0
  1. using System;
  2.  
  3. class MergeSortAlg
  4. {
  5.     static void Main()
  6.     {
  7.         int[] numArray = {1, -10,20,100,2,4,5,8,29,2};
  8.            
  9.         Console.WriteLine("Before sorting: \n{0}", string.Join(" ", numArray));
  10.  
  11.         //sorting
  12.         MergeSort(numArray, 0, numArray.Length - 1);
  13.  
  14.         Console.WriteLine("After sorting: \n{0}", string.Join(" ", numArray));
  15.  
  16.     }
  17.  
  18.     public static void MergeSort(int[] inputArray, int left, int right)
  19.     {
  20.         if (left < right)
  21.         {
  22.             int md = (left + right) / 2;
  23.  
  24.             MergeSort(inputArray, left, md);
  25.             MergeSort(inputArray, md + 1, right);
  26.  
  27.             //Merge
  28.             int[] leftArray = new int[md - left + 1];
  29.             int[] rightArray = new int[right - md];
  30.  
  31.             Array.Copy(inputArray, left, leftArray, 0, md - left + 1);
  32.             Array.Copy(inputArray, md + 1, rightArray, 0, right - md);
  33.  
  34.             int lIndex = 0;
  35.             int rIndex = 0;
  36.             for (int index = left; index <= right; index++)
  37.             {
  38.                 if (lIndex == leftArray.Length) //do we have 0 elements
  39.                 {
  40.                     inputArray[index] = rightArray[rIndex];
  41.                     rIndex++;
  42.                 }
  43.                 else if (rIndex == rightArray.Length) // do we have 0 elements
  44.                 {
  45.                     inputArray[index] = leftArray[lIndex];
  46.                     lIndex++;
  47.                 }
  48.                 else if (leftArray[lIndex] <= rightArray[rIndex])
  49.                 {
  50.                     inputArray[index] = leftArray[lIndex];
  51.                     lIndex++;
  52.                 }
  53.                 else
  54.                 {
  55.                     inputArray[index] = rightArray[rIndex];
  56.                     rIndex++;
  57.                 }
  58.             }
  59.         }
  60.     }      
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement