Advertisement
m1okgoodyes

sortQuick

Apr 10th, 2022
1,190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.51 KB | None | 0 0
  1. using System;
  2.  
  3. namespace QuickSortAlgorithm
  4. {
  5.     class Program
  6.     {
  7.         static void Main()
  8.         {
  9.             int[] inputArray = { 9, 12, 9, 2, 17, 1, 6 };
  10.  
  11.             int[] sortedArray = QuickSort(inputArray, 0, inputArray.Length - 1);
  12.  
  13.             Console.WriteLine($"Sorted array: {string.Join(", ", sortedArray)}");
  14.  
  15.             Console.ReadLine();
  16.         }
  17.  
  18.         private static int[] QuickSort(int[] array, int minIndex, int maxIndex)
  19.         {
  20.             if (minIndex >= maxIndex)
  21.             {
  22.                 return array;
  23.             }
  24.  
  25.             int pivotIndex = GetPivotIndex(array, minIndex, maxIndex);
  26.  
  27.             QuickSort(array, minIndex, pivotIndex - 1);
  28.  
  29.             QuickSort(array, pivotIndex + 1, maxIndex);
  30.  
  31.             return array;
  32.         }
  33.  
  34.         private static int GetPivotIndex(int[] array, int minIndex, int maxIndex)
  35.         {
  36.             int pivot = minIndex - 1;
  37.  
  38.             for (int i = minIndex; i <= maxIndex; i++)
  39.             {
  40.                 if (array[i] < array[maxIndex])
  41.                 {
  42.                     pivot++;
  43.                     Swap(ref array[pivot], ref array[i]);
  44.                 }
  45.             }
  46.  
  47.             pivot++;
  48.             Swap(ref array[pivot], ref array[maxIndex]);
  49.  
  50.             return pivot;
  51.         }
  52.  
  53.         private static void Swap(ref int leftItem, ref int rightItem)
  54.         {
  55.             int temp = leftItem;
  56.  
  57.             leftItem = rightItem;
  58.  
  59.             rightItem = temp;
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement