Advertisement
Neychok

Quick sort

May 15th, 2020
1,241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.99 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace Quick_Sort
  7. {
  8.     class Program
  9.     {
  10.         private static void Quick_Sort(int[] arr, int left, int right)
  11.         {
  12.             if (left < right)
  13.             {
  14.                 int pivot = Partition(arr, left, right);
  15.  
  16.                 if (pivot > 1)
  17.                 {
  18.                     Quick_Sort(arr, left, pivot - 1);
  19.                 }
  20.                 if (pivot + 1 < right)
  21.                 {
  22.                     Quick_Sort(arr, pivot + 1, right);
  23.                 }
  24.             }
  25.  
  26.         }
  27.  
  28.         private static int Partition(int[] arr, int left, int right)
  29.         {
  30.             int pivot = arr[left];
  31.             while (true)
  32.             {
  33.  
  34.                 while (arr[left] < pivot)
  35.                 {
  36.                     left++;
  37.                 }
  38.  
  39.                 while (arr[right] > pivot)
  40.                 {
  41.                     right--;
  42.                 }
  43.  
  44.                 if (left < right)
  45.                 {
  46.                     if (arr[left] == arr[right]) return right;
  47.  
  48.                     int temp = arr[left];
  49.                     arr[left] = arr[right];
  50.                     arr[right] = temp;
  51.  
  52.  
  53.                 }
  54.                 else
  55.                 {
  56.                     return right;
  57.                 }
  58.             }
  59.         }
  60.         static void Main(string[] args)
  61.         {
  62.             int[] arr = new int[] { 2, 5, -4, 11, 0, 18, 22, 67, 51, 6 };
  63.  
  64.             Console.WriteLine("Original array : ");
  65.             foreach (var item in arr)
  66.             {
  67.                 Console.Write(" " + item);
  68.             }
  69.             Console.WriteLine();
  70.  
  71.             Quick_Sort(arr, 0, arr.Length - 1);
  72.  
  73.             Console.WriteLine();
  74.             Console.WriteLine("Sorted array : ");
  75.  
  76.             foreach (var item in arr)
  77.             {
  78.                 Console.Write(" " + item);
  79.             }
  80.             Console.WriteLine();
  81.         }
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement