Advertisement
gabi11

Algorithms - 1. Merge Sort

Sep 8th, 2019
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.08 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace Algorithms
  6. {
  7.     class Program
  8.     {
  9.         static void Sort(int[] arr, int startIndex, int endIndex)
  10.         {
  11.             if (startIndex >= endIndex)
  12.             {
  13.                 return;
  14.             }
  15.  
  16.             int midIndex = (startIndex + endIndex) / 2;
  17.  
  18.             Sort(arr, startIndex, midIndex);
  19.             Sort(arr, midIndex + 1, endIndex);
  20.  
  21.             Merge(arr, startIndex, midIndex, endIndex);
  22.         }
  23.  
  24.         private static void Merge(int[] arr, int startIndex, int midIndex, int endIndex)
  25.         {
  26.             if (midIndex < 0 || midIndex + 1 >= arr.Length
  27.                 || arr[midIndex] <= arr[midIndex + 1])
  28.             {
  29.                 return;
  30.             }
  31.  
  32.             int[] tempArr = new int[arr.Length];
  33.  
  34.             for (int i = startIndex; i <= endIndex; i++)
  35.             {
  36.                 tempArr[i] = arr[i];
  37.             }
  38.  
  39.             int leftIndex = startIndex;
  40.             int rightIndex = midIndex + 1;
  41.  
  42.             for (int i = startIndex; i <= endIndex; i++)
  43.             {
  44.                 if (leftIndex > midIndex)
  45.                 {
  46.                     arr[i] = tempArr[rightIndex];
  47.                     rightIndex++;
  48.  
  49.                     // arr[i] = tempArr[rightIndex++]; - кратък запис на горните 2
  50.                 }
  51.  
  52.                 else if (rightIndex > endIndex)
  53.                 {
  54.                     arr[i] = tempArr[leftIndex++];
  55.                 }
  56.  
  57.                 else if (tempArr[leftIndex] <= tempArr[rightIndex])
  58.                 {
  59.                     arr[i] = tempArr[leftIndex++];
  60.                 }
  61.  
  62.                 else
  63.                 {
  64.                     arr[i] = tempArr[rightIndex++];
  65.                 }
  66.             }
  67.         }
  68.  
  69.         static void Main(string[] args)
  70.         {
  71.  
  72.             var numbers = Console.ReadLine().Split().Select(int.Parse).ToArray();
  73.  
  74.             Sort (numbers, 0, numbers.Length - 1);
  75.  
  76.             Console.WriteLine(string.Join(" ", numbers));
  77.         }
  78.  
  79.     }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement