C
36
Quicksort
Guest on 1st August 2022 12:41:53 AM
/* Quicksort algorithm */
/* Michel Vallieres
*
* ref: http://cprogramminglanguage.net/quicksort-algorithm-c-source-code.aspx
* Numerical Recipes
*/
void swap(double *x, double *y)
{
double temp;
temp = *x;
*x = *y;
*y = temp;
}
int choose_pivot(int i, int j)
{
return i + (j - i) / 2;
}
/* sort the list from list[m] to list[n] */
void quicksort(double list[], int m, int n)
{
int i, j, k;
double key;
if (m < n) {
k = choose_pivot(m, n);
swap(&list[m], &list[k]);
key = list[m];
i = m + 1;
j = n;
while (1) {
while ((i <= n) && (list[i] <= key))
i++;
while ((j >= m) && (list[j] > key))
j--;
if (i >= j)
break;
swap(&list[i], &list[j]);
}
// put the pivot back in
swap(&list[m], &list[j]);
// recursively sort the sub-lists
quicksort(list, m, j - 1);
quicksort(list, j + 1, n);
}
}
void sort(int list_size, double *list)
{
quicksort(list, 0, list_size - 1);
}