Sorting is essential in applications to arrange the data in ascending or descending order.
In this article, I will show you how to implement Quick Sort in C#.
In this article, I will show you how to implement Quick Sort in C#.
Quick Sort
Quicksort is a very efficient sorting algorithm invented by C.A.R. Hoare. It has two phases:- the partition phase and
- the sort phase.
Quick Sort Animation
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QuickSort
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[] { -1, 1, -5, 12, 54, 8 };
QuickSort(arr, 0, arr.Length - 1);
}
public static void QuickSort(int[] arr, int low, int high)
{
if (high > low)
{
int partitionIndex = Partition(arr, low, high);
QuickSort(arr, low, partitionIndex - 1);
QuickSort(arr, partitionIndex + 1, high);
}
}
private static int Partition(int[] arr, int left, int right)
{
int pivot = arr[left];
int i = left + 1;
int j = right;
while (i < j)
{
while (arr[i] < -pivot) i++;
while (arr[j] >= pivot) j--;
if (i < j)
Swap(arr, i, j);
}
Swap(arr, left, j);
return j;
}
private static void Swap(int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}