Here is a simple quicksort algorithm which sorts an integer array from lowest to highest (inplace). Useful if you want to study Lite-C syntax and so on.
Here it is:
Code:
//- quicksort --------------------------------------------------------
//prototypes
int partition (int* A, int l, int r);
void quicksort (int* A, int l, int r);
//----------------------------------------------------------------
//call quicksort with l = 0 and r = number of elements - 1
//sorts inplace from lowest to highest!
//----------------------------------------------------------------
void quicksort (int* A, int l, int r)
{
if (l < r)
{
int q = partition(A, l, r);
quicksort(A, l, q);
quicksort(A, q+1, r);
}
}
//------------------------------------------------------------
//determines the pivot element which serves
//for the partioning
//------------------------------------------------------------
int partition (int* A, int l, int r)
{
int x = A[(int)((l+r)/2)];
int i = l-1;
int j = r+1;
while (1) {
do {j--;} while (A[j] > x);
do {i++;} while (A[i] < x);
if (i < j) {
int help;
help = A[j];
A[j] = A[i];
A[i] = help;
} else {
return j;
}
}
}
//- demo -------------------------------------------------------------
void main()
{
int arr [] = {9,6,2,8,1,6,5,4,8};
quicksort(arr, 0, 8);
int i = 0;
while (1) {
if (i < 9) {
error(str_for_num(str_create(""), arr[i]));
i++;
}
wait(1);
}
}
Have fun!