vojta249

Maturita_21 - quicksort

May 5th, 2022
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.13 KB | None | 0 0
  1. using System;
  2.  
  3. public class Program
  4. {
  5.     public static void Main()
  6.     {
  7.         int[] arr = { 67, 12, 95, 56, 85, 1, 100, 23, 60, 9 };
  8.         int n = 10, i;
  9.         Console.WriteLine("Quick Sort");
  10.         Console.Write("Původní pole: ");
  11.         for (i = 0; i < n; i++)
  12.         {
  13.             Console.Write(arr[i] + " ");
  14.         }
  15.  
  16.         quickSort(arr, 0, 9);
  17.         Console.Write("\nSetřízené pole: ");
  18.         for (i = 0; i < n; i++)
  19.         {
  20.             Console.Write(arr[i] + " ");
  21.         }
  22.         Console.ReadKey();
  23.     }
  24.  
  25.     static int Partition(int[] arr, int left, int right)
  26.     {
  27.         int pivot;
  28.         pivot = arr[left];
  29.         while (true)
  30.         {
  31.             while (arr[left] < pivot)
  32.             {
  33.                 left++;
  34.             }
  35.  
  36.             while (arr[right] > pivot)
  37.             {
  38.                 right--;
  39.             }
  40.  
  41.             if (left < right)
  42.             {
  43.                 int temp = arr[right];
  44.                 arr[right] = arr[left];
  45.                 arr[left] = temp;
  46.             }
  47.             else
  48.             {
  49.                 return right;
  50.             }
  51.         }
  52.     }
  53.  
  54.     static void quickSort(int[] arr, int left, int right)
  55.     {
  56.         int pivot;
  57.         if (left < right)
  58.         {
  59.             pivot = Partition(arr, left, right);
  60.             if (pivot > 1)
  61.             {
  62.                 quickSort(arr, left, pivot - 1);
  63.             }
  64.  
  65.             if (pivot + 1 < right)
  66.             {
  67.                 quickSort(arr, pivot + 1, right);
  68.             }
  69.         }
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment