Skip to content

Instantly share code, notes, and snippets.

@kmb385
Created January 13, 2022 07:48
Show Gist options
  • Save kmb385/50d0a0fc4b63dee8029ab394dec0519b to your computer and use it in GitHub Desktop.
Save kmb385/50d0a0fc4b63dee8029ab394dec0519b to your computer and use it in GitHub Desktop.
C# QuickSort
int[] nums = { 23, 300, 2400, 2300, 100, 1, 10, 20, 15 };
QuickSort(nums, 0, nums.Length - 1);
Console.WriteLine(String.Join(",", nums));
void QuickSort(int[] nums, int low, int high)
{
if(low < high)
{
int pivot = Partition(nums, low, high);
QuickSort(nums, low, pivot - 1);
QuickSort(nums, pivot + 1, high);
}
}
int Partition(int[] nums, int low, int high)
{
int i = low - 1;
int pivot = nums[high];
for(int j = low; j < high; j++)
{
if(nums[j] < pivot)
{
Swap(nums, j, ++i);
}
}
Swap(nums, high, ++i);
return i;
}
void Swap(int[] nums, int j, int i)
{
int tmp = nums[j];
nums[j] = nums[i];
nums[i] = tmp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment