Advertisement
APXOHT

Untitled

Jan 6th, 2013
793
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.91 KB | None | 0 0
  1. using System;
  2.  
  3. class MergeSortAlgorithm
  4. {
  5.     //merges two arrays
  6.     static int[] MergeArrays(int[] left, int[] right)
  7.     {
  8.         int[] result = new int[left.Length + right.Length];
  9.  
  10.         int leftIncrease = 0;
  11.         int rightIncrease = 0;
  12.  
  13.         for (int i = 0; i < result.Length; i++)
  14.         {
  15.             if (rightIncrease == right.Length || ((leftIncrease < left.Length) && (left[leftIncrease] <= right[rightIncrease])))
  16.             {
  17.                 result[i] = left[leftIncrease];
  18.                 leftIncrease++;
  19.             }
  20.             else if (leftIncrease == left.Length || ((rightIncrease < right.Length) && (right[rightIncrease] <= left[leftIncrease])))
  21.             {
  22.                 result[i] = right[rightIncrease];
  23.                 rightIncrease++;
  24.             }
  25.         }
  26.  
  27.         return result;
  28.     }
  29.  
  30.     //recursevily merges two arrays
  31.     static int[] MergeSort(int[] array)
  32.     {
  33.         if (array.Length <= 1)
  34.         {
  35.             return array;
  36.         }
  37.  
  38.         int middle = array.Length / 2;
  39.         int[] leftArray = new int[middle];
  40.         int[] rightArray = new int[array.Length - middle];
  41.  
  42.         for (int i = 0; i < middle; i++)
  43.         {
  44.             leftArray[i] = array[i];
  45.         }
  46.  
  47.         for (int i = middle, j = 0; i < array.Length; i++, j++)
  48.         {
  49.             rightArray[j] = array[i];
  50.         }
  51.  
  52.         leftArray = MergeSort(leftArray);
  53.         rightArray = MergeSort(rightArray);
  54.  
  55.         return MergeArrays(leftArray, rightArray);
  56.     }
  57.  
  58.     static void PrintArray(int[] array)
  59.     {
  60.         for (int i = 0; i < array.Length; i++)
  61.         {
  62.             Console.Write(array[i] + " ");
  63.         }
  64.         Console.WriteLine();
  65.     }
  66.  
  67.     static void Main()
  68.     {
  69.  
  70.         int[] arrayOfIntegers = { 1, 5, 7, 8, 9, 3, 5, 6, 7 };
  71.         int[] sortedArray = MergeSort(arrayOfIntegers);
  72.  
  73.         PrintArray(sortedArray);
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement