Advertisement
Klaxon

[C# Arrays] Merge Sort Algorithm

Sep 30th, 2013
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.97 KB | None | 0 0
  1. // 13. * Write a program that sorts an array of integers using the merge sort algorithm (find it in Wikipedia).
  2.  
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Text;
  6.  
  7. class MergeSortAlgorithm // With some help from the web
  8. {
  9.     // Main magic
  10.     static public void DoMerge(int[] numbers, int left, int mid, int right)
  11.     {
  12.         // help variables
  13.         int[] temp = new int[25];
  14.         int i = 0;
  15.         int leftEnd = 0;
  16.         int numElements = 0;
  17.         int tmpPos = 0;
  18.  
  19.         leftEnd = (mid - 1);
  20.         tmpPos = left;
  21.         numElements = (right - left + 1);
  22.  
  23.         while ((left <= leftEnd) && (mid <= right))
  24.         {
  25.             if (numbers[left] <= numbers[mid])
  26.             {
  27.                 temp[tmpPos++] = numbers[left++];
  28.             }
  29.             else
  30.             {
  31.                 temp[tmpPos++] = numbers[mid++];
  32.             }
  33.         }
  34.  
  35.         while (left <= leftEnd)
  36.         {
  37.             temp[tmpPos++] = numbers[left++];
  38.         }
  39.  
  40.         while (mid <= right)
  41.         {
  42.             temp[tmpPos++] = numbers[mid++];
  43.         }
  44.  
  45.         for (i = 0; i < numElements; i++)
  46.         {
  47.             numbers[right] = temp[right];
  48.             right--;
  49.         }
  50.     }
  51.  
  52.     // Recursive logic
  53.     static public void MergeSortRecursive(int[] numbers, int left, int right)
  54.     {
  55.         int mid;
  56.  
  57.         if (right > left)
  58.         {
  59.             mid = (right + left) / 2;
  60.             MergeSortRecursive(numbers, left, mid);
  61.             MergeSortRecursive(numbers, (mid + 1), right);
  62.             DoMerge(numbers, left, (mid + 1), right);
  63.         }
  64.     }
  65.  
  66.     // Printing
  67.     static void Main(string[] args)
  68.     {
  69.         int[] numbers = { 3, 8, 7, 5, 2, 1, 9, 6, 4 };
  70.         int len = 9;
  71.  
  72.         Console.WriteLine("MergeSort by recursive method:");
  73.         MergeSortRecursive(numbers, 0, len - 1);
  74.         for (int i = 0; i < 9; i++)
  75.         {
  76.             Console.WriteLine(numbers[i]);
  77.         }
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement