Skip to content

Instantly share code, notes, and snippets.

@vmeln
Created December 9, 2013 10:28
Show Gist options
  • Save vmeln/7870196 to your computer and use it in GitHub Desktop.
Save vmeln/7870196 to your computer and use it in GitHub Desktop.
Quick Sort C#
using System;
namespace QuickSort
{
class Program
{
static void Main()
{
int[] arrayToSort = { 1, 340, 20, 40, 12, 15 };
Sort(arrayToSort, 0, arrayToSort.Length - 1);
for (var i = 0; i < arrayToSort.Length; i++)
{
Console.Write("{0} ", arrayToSort[i]);
}
Console.WriteLine();
}
private static void Sort(int[] input, int low, int high)
{
int i = low, j = high;
int pivot = input[(i + j) / 2];
while (i <= j)
{
while (input[i] < pivot) i++;
while (input[j] > pivot) j--;
if (i <= j)
{
Swap(ref input[i], ref input[j]);
i++;
j--;
}
}
if (low < j)
Sort(input, low, j);
if (i < high)
Sort(input, i, high);
}
static void Swap<T>(ref T lhs, ref T rhs)
{
T temp = lhs;
lhs = rhs;
rhs = temp;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment