快速排序是排序算法中用的最多,时间最快的算法。要熟练掌握。
#include<iostream>
using namespace std;
int a[] = { 49, 38, 65, 97, 76, 13, 27, 49 };
void QuickSort(int n,int low,int high)
{
if (low >= high)
return;
int i = low, j = high;
int key = a[i];
while (i<j)
{
while (i < j && a[j] >= key)//注意此处的等于号
{
j--;
}
a[i] = a[j];
while (i < j&&a[i] <= key)//注意此处的等于号
{
i++;
}
a[j] = a[i];
}
a[i] = key;
QuickSort(n,low,i-1);
QuickSort(n,i+1,high);
}
int main()
{
QuickSort(sizeof(a) / sizeof(a[0]), 0, sizeof(a) / sizeof(a[0])-1);
for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++)
{
cout << a[i]<<" ";
}
}