Advertisement
Falexom

Untitled

Feb 3rd, 2022
1,265
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 Merges
  4. {
  5.     void sort(int[] array)
  6.     {
  7.         if (array.Length < 2)
  8.         {
  9.             return;
  10.         }
  11.         int middle = array.Length / 2;
  12.         int[] left = new int[middle];
  13.         int[] right = new int[array.Length - middle];
  14.  
  15.         for (int i = 0; i < middle; i++)
  16.         {
  17.             left[i] = array[i];
  18.         }
  19.         for (int i = middle; i < array.Length; i++)
  20.         {
  21.             right[i - middle] = array[i];
  22.         }
  23.         sort(left);
  24.         sort(right);
  25.         merge(array, left, right);
  26.     }
  27.  
  28.     void merge(int[] res, int[] left, int[] right)
  29.     {
  30.         int index1 = 0;
  31.         int index2 = 0;
  32.  
  33.         int result = 0;
  34.  
  35.         while (index1 < left.Length && index2 < right.Length)
  36.         {
  37.             if (left[index1] <= right[index2])
  38.             {
  39.                 res[result] = left[index1];
  40.                 index1++;
  41.             }
  42.             else
  43.             {
  44.                 res[result] = right[index2];
  45.                 index2++;
  46.             }
  47.             result++;
  48.         }
  49.         while (index1 < left.Length)
  50.         {
  51.             res[result] = left[index1];
  52.             index1++;
  53.             result++;
  54.         }
  55.         while (index2 < right.Length)
  56.         {
  57.             res[result] = right[index2];
  58.             index2++;
  59.             result++;
  60.         }
  61.     }
  62.  
  63.  
  64.    static void print(int[] array)
  65.     {
  66.         int n = array.Length;
  67.         for (int i = 0; i < n; ++i)
  68.             Console.Write(array[i] + "");
  69.         Console.WriteLine();
  70.     }
  71.  
  72.     public static void Main(String[] ar)
  73.     {
  74.         int[] mass = { 11, 66, 44, 55, 77, 99, 22, 88, 33 };
  75.         print(mass);
  76.         Merges ob = new Merges();
  77.         ob.sort(mass);
  78.         Console.WriteLine("Got it!");
  79.         print(mass);
  80.  
  81.     }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement