将最左边的点设置为基准点,小的放到左边,大的放到右边,然后递归直到left>=right为止。
#include <iostream>
using namespace std;
void quickSort(int array[], int left, int right)
{
if (left >= right)
{
return;
}
int base = array[left];
int leftIndex = left;
int rightIndex = right;
while (leftIndex < rightIndex)
{
while (leftIndex < rightIndex && array[rightIndex] >= base)
{
rightIndex--;
}
while (leftIndex < rightIndex && array[leftIndex] <= base)
{
leftIndex++;
}
if (leftIndex < rightIndex)
{
int temp = array[leftIndex];
array[leftIndex] = array[rightIndex];
array[rightIndex] = temp;
}
}
array[left] = array[leftIndex];
array[leftIndex] = base;
quickSort(array, left, rightIndex - 1);
quickSort(array, rightIndex + 1, right);
}
int main()
{
int a[] = {9,8,7,3,5,1,4};
quickSort(a, 0, 6);
for (auto n : a)
{
cout << n << endl;
}
return 0;
}