Last active
December 12, 2015 10:39
-
-
Save darklight721/4760612 to your computer and use it in GitHub Desktop.
Quicksort implementation in C.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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