#include <stdio.h>
void exchange(int *array, int p1, int p2)
{
if (p1 == p2)
return;
int temp = array[p1];
array[p1] = array[p2];
array[p2] = temp;
}
int partition(int *array, int left, int right)
{
int pivot = array[right];
int index = left - 1;//storage postion,start with outside
int cur;
for (cur = left; cur < right; cur++)
{
if (array[cur] <= pivot)
{
exchange(array, ++index, cur);//exchange smaller data than pivot to index postion and increase the index
}
}
exchange(array, ++index, right);//after exchange all data smaller than pivot, exchange the pivot to the next postion index's next psotion
return index;
}
void quickSort(int *array, int left, int right)
{
if (left < right)
{
int partitionPos = partition(array, left, right); //get the partition postion
quickSort(array, left, partitionPos - 1); //Sorts the left interval of the array
quickSort(array, partitionPos + 1, right); //Sorts the right interval of the arrays
}
}
void main()
{
int array[5] = {1, 7, 9, 2, 4};
printf("array=");
int i;
for (i = 0; i < sizeof(array); i++)
{
printf("%d ", array[i]);
}
printf("\n");
quickSort(array, 0, sizeof(array) - 1);
printf("array=");
for (i = 0; i < sizeof(array); i++)
{
printf("%d ", array[i]);
}
return;
}