https://www.luogu.org/problem/P1177
#include <iostream>
#include <fstream>
using namespace std;
int n;
int inputList[100000];
bool test = false;
void swap(int i, int j)
{
if(test)
{
cout << "i=" << i << ",j=" << j << endl;
}
if (i == j)
{
return;
}
int tmp = inputList[i];
inputList[i] = inputList[j];
inputList[j] = tmp;
//cout << i << "," << j << "-";
//for (int t = 0; t < n; t++)
//{
// cout << inputList[t] << " ";
//}
//cout <<endl;
}
// 备注:此方案会超时,应该是key的取值不合适
// [start, end)
void quickSort(int start, int end)
{
if (start+1 >= end)
{
return;
}
int key = inputList[start];
int i = start;
int j = end - 1;
bool bFront = false;
while ( i != j)
{
if (bFront)
{
if (inputList[i] >= key)
{
//cout << start << "," << end << " , ";
swap(i, j);
bFront = false;
j--;
}
else
{
i++;
}
}
else
{
if (inputList[j] < key)
{
//cout << start << "," << end << " , ";
swap(i, j);
bFront = true;
i++;
}
else
{
j--;
}
}
}
quickSort(start, i);
quickSort(i+1, end);
}
// 优化后方案,key取中间值
// [start, end]
void quickSort2(int start, int end)
{
//if (start+1 >= end)
//{
// return;
//}
int key = inputList[(start+end)/2];
if(test)
{
cout << "[" << start << "," << end << "] key=" << key << endl;
}
int i = start;
int j = end;
while ( i <= j)
{
while(i <= end && inputList[i] < key)
{
i++;
}
//while(j >= start && inputList[j] >= key)
while(j >= start && inputList[j] > key)
{
j--;
}
if (i <= j)
{
swap(i, j);
i++;
j--;
}
}
if(i < end && i > start)
{
quickSort2(i, end);
}
if (j > start && j < end)
{
quickSort2(start, j);
}
}
int main()
{
//test = true;
if (test)
{
ifstream f("C:\\Users\\suyang\\Downloads\\testdata (5).in");
if (f)
{
cout << "f is ok" << endl;
}
else
{
cout << "f is error" << endl;
}
f >> n;
for(int i = 0; i < n; i++)
{
f>>inputList[i];
}
f.close();
n = 50;
}
else
{
cin >> n;
for(int i = 0; i < n; i++)
{
cin>>inputList[i];
}
}
quickSort2(0, n-1);
//quickSort(0, n);
if (test)
{
ofstream f("luogu_out.txt");
if (f)
{
cout << "f is ok" << endl;
}
else
{
cout << "f is error" << endl;
}
//f << inputList[0];
//for(int i = 1; i < n; i++)
//{
// f << " " << inputList[i];
//}
//f << endl;
for(int i = 0; i < n; i++)
{
f << inputList[i] << endl;
}
f.close();
}
else
{
cout << inputList[0];
for(int i = 1; i < n; i++)
{
cout << " " << inputList[i];
}
cout << endl;
}
return 0;
}