Skip to content

Instantly share code, notes, and snippets.

@darklight721
Last active December 12, 2015 10:39
Show Gist options
  • Save darklight721/4760612 to your computer and use it in GitHub Desktop.
Save darklight721/4760612 to your computer and use it in GitHub Desktop.
Quicksort implementation in C.
void quick_sort(int list[], int left, int right)
{
if (left < right) {
int pivot = (left + right) / 2; // left + (right - left) / 2 is safer to use for large lists
pivot = partition(list, left, right, pivot);
quick_sort(list, left, pivot - 1);
quick_sort(list, pivot + 1, right);
}
}
int partition(int list[], int left, int right, int pivot)
{
int pivotVal = list[pivot];
swap(&(list[pivot]), &(list[right]));
int store = left;
for (int i = left; i <= right - 1; i++) {
if (list[i] < pivotVal) {
swap(&(list[i]), &(list[store]));
store++;
}
}
swap(&(list[store]), &(list[right]));
return store;
}
void swap(int *a, int *b)
{
int c = *a;
*a = *b;
*b = c;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment