Created
November 5, 2023 22:58
-
-
Save jimdiroffii/c7bf3428005b1630b3c3da7766efd5e3 to your computer and use it in GitHub Desktop.
K&R Recursive Quicksort in C
This file contains hidden or 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
/* Pg. 87 - The C Programming Language (2nd Ed) - Recursive Quicksort */ | |
/* qsort: sort v[left]..v[right into increasing order */ | |
void qsort(int v[], int left, int right) | |
{ | |
int i, last; | |
void swap(int v[], int i, int j); | |
if (left >= right) /* do nothing if array contains */ | |
return; /* fewer than two elements */ | |
swap(v, left, (left + right) / 2); /* move partition elem */ | |
last = left; /* to v[0] */ | |
for (i = left + 1; i <= right; i++) /* partition */ | |
if (v[i] < v[left]) | |
swap(v, ++last, i); | |
swap(v, left, last); /* restore partition elem */ | |
qsort(v, left, last - 1); | |
qsort(v, last + 1, right); | |
} | |
/* swap: interchange v[i] and v[j] */ | |
void swap(int v[], int i, int j) | |
{ | |
int temp; | |
temp = v[i]; | |
v[i] = v[j]; | |
v[j] = temp; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment