Advertisement
thegreen9

Сортировка массива

Mar 28th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.60 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace SecondLab
  8. {
  9.     class Program
  10.     {
  11.         public static void mergeSort(int[] arrayList)
  12.         {
  13.             //уже отсортирован
  14.             if (arrayList.Length < 2)
  15.                 return;
  16.             //разбиение на две части
  17.             //если размер массива нечетный, то вторая часть возьмет еще 1 дополнителньый элемент
  18.             int[] firstPart = new int[arrayList.Length / 2];
  19.             int[] secondPart = new int[arrayList.Length - firstPart.Length];
  20.             for (int z = 0; z < firstPart.Length; ++z)
  21.                 firstPart[z] = arrayList[z];
  22.             for (int z = 0; z < secondPart.Length; ++z)
  23.                 secondPart[z] = arrayList[z + firstPart.Length];
  24.             //рекурсивная сортировка обоих из этих двух частей
  25.             mergeSort(firstPart);
  26.             mergeSort(secondPart);
  27.  
  28.             //слияние частей
  29.             int i = 0;//индекс целого массива
  30.             int j = 0;//индекс первой части
  31.             int k = 0;//индекс второй части
  32.             //добавление элементов к целому массиву пока количество эелментов какой то части не кончится
  33.             while (j != firstPart.Length && k != secondPart.Length)
  34.             {
  35.                 if (firstPart[j] < secondPart[k])
  36.                 {
  37.                     arrayList[i] = firstPart[j];
  38.                     ++j;
  39.                 }
  40.                 else
  41.                 {
  42.                     arrayList[i] = secondPart[k];
  43.                     ++k;
  44.                 }
  45.                 ++i;
  46.             }
  47.             //добавление оставшихся элементов
  48.             while (j != firstPart.Length)
  49.             {
  50.                 arrayList[i] = firstPart[j];
  51.                 ++j;
  52.                  ++i;
  53.             }
  54.             while (k != secondPart.Length)
  55.             {
  56.                 arrayList[i] = secondPart[k];
  57.                 ++k;
  58.                 ++i;
  59.             }
  60.         }
  61.  
  62.         static void Main(string[] args)
  63.         {
  64.             int[] array = { 5, 4, 3, 1, 4 };
  65.             mergeSort(array);
  66.             for (int i = 0; i < array.Length; ++i)
  67.                 Console.Write(array[i] + " ");
  68.             Console.ReadKey();
  69.         }
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement