荷蘭國旗優化快速排序
阿新 • • 發佈:2018-12-09
#include<iostream>
#include<cstdio>
using namespace std;
int p1, p2;
void swap(int a[], int x, int y)
{
int temp = a[x];
a[x] = a[y];
a[y] = temp;
}
void partition(int a[], int l, int r)
{
int less = l - 1;
int more = r;
while(l < more)
{
if(a[l] < a[r])
{
swap(a, ++less, l++);
}
else if(a[l] > a[r])
{
swap(a, --more, l);
}
else
{
l++;
}
}
swap(a, more, r);
p1 = less + 1;
p2 = more;
}
void quickSort(int a[], int l, int r)
{
if(l < r)
{
partition(a, l, r);
quickSort(a, l, p1 - 1 );
quickSort(a, p2 + 1, r);
}
}
int main()
{
int a[7] = {8, 7, 3, 9, 2, 0, 6};
quickSort(a, 0, 6);
for(int i = 0; i < 7; i++)
{
cout << a[i] << " ";
}
}