快速排序的一种代码尝试
一体 2019-05-07 08:03:01 #include<iostream>
using namespace std;
void partition(int list[], int p, int v)
{
int an = 0; //change searching-sequence
int min = p; //save the edge information
int max = v; //....................
while(p != v)
{
if(an == 0)
{
for(int i = v; i > p; i--)
{
if(list[i] <= list[p])
{
int temp = list[p];
list[p] = list[i];
list[i] = temp;
an = 1;
v = p + 1;
p = i;
break;
}
}
if(an == 0) //is already partition
{
v = p;
}
}
else
{
for(int i = v; i < p; i++)
{
if(list[i] >= list[p])
{
int temp = list[p];
list[p] = list[i];
list[i] = temp;
an = 0;
v = p - 1;
p = i;
break;
}
}
if(an == 1) //......................
{
v = p;
}
}
}
if(p - min > 1) //recursive call
{
partition(list, min, p - 1);
}
if(max - p > 1) //...........
{
partition(list, p + 1, max);
}
}
int main()
{
cout << "Enter size: ";
int size;
cin >> size;
cout << "Enter list: ";
int list[size];
for(int i = 0; i < size; i++)
{
cin >> list[i];
}
partition(list, 0, size - 1);
cout << "After sorted, the list is: ";
for(int i = 0; i < size; i++)
{
cout << list[i] << " ";
}
return 0;
}