Skip to content

Instantly share code, notes, and snippets.

@VegaFromLyra
Created May 29, 2015 17:53
Show Gist options
  • Save VegaFromLyra/e5ff20f3f3a18897a1b2 to your computer and use it in GitHub Desktop.
Save VegaFromLyra/e5ff20f3f3a18897a1b2 to your computer and use it in GitHub Desktop.
QuickSort
using System;
namespace QuickSort
{
public class Program
{
public static void Main(string[] args)
{
int[] arr = {3, 6, 1, 5, 4};
Console.WriteLine("Input is");
display(arr);
quickSort(arr);
Console.WriteLine("Output is");
display(arr);
}
static void display(int[] arr) {
foreach (var item in arr) {
Console.Write(item + " ");
}
Console.WriteLine(" ");
}
static void quickSort(int[] input) {
quickSort(input, 0, input.Length - 1);
}
static void quickSort(int[] arr, int left, int right) {
int index = partition(arr, left, right);
if (left < index - 1) {
quickSort(arr, left, index - 1);
}
if (index < right) {
quickSort(arr, index, right);
}
}
static int partition(int[] arr, int left, int right) {
int pivot = arr[(left + right) / 2];
while (left <= right) {
while (arr[left] < pivot) {
left++;
}
while (arr[right] > pivot) {
right--;
}
if (left <= right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
return left;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment