#include <stdio.h>
#include <stdlib.h>
int partition(int*, int, int);
void qSort(int*, int, int);
void swap(int*, int*);
int main(void)
{
int i;
int array[] = {11, 5, 20, 5, 100, 88, -987, 666, 0, 11, 11};
for (i = 0; i < 11; ++i)
{
printf("%d ", array[i]);
}
printf("\n");
qSort(array, 0, 10);
for (i = 0; i < 11; ++i)
{
printf("%d ", array[i]);
}
printf("\n");
return 0;
}
/*
int partition(int *array, int low, int high)
{
int i = low + 1;
int j = high;
int pivot = array[low];
while (i <= j)
{
if (array[i] <= pivot)
{
++i;
}
else if (array[j] > pivot)
{
--j;
}
else
{
swap(&array[i], &array[j]);
}
}
array[low] = array[j];
array[j] = pivot;
return j;
}
*/
int partition(int *array, int low, int high)
{
int i = low;
int j = high + 1;
int pivot = array[low];
while (i < j)
{
while (array[++i] <= pivot);
while (array[--j] > pivot);
if (i >= j) break;
swap(&array[i], &array[j]);
}
array[low] = array[j];
array[j] = pivot;
return j;
}
void qSort(int *array, int low, int high)
{
int q;
if (low < high)
{
q = partition(array, low, high);
qSort(array, low, q - 1);
qSort(array, q + 1, high);
}
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}