Pagini recente » Cod sursa (job #473560) | Cod sursa (job #1244936) | Cod sursa (job #1937334)
#include <fstream>
#include <vector>
using namespace std;
vector <int> a;
void write()
{
ofstream cout("algsort.out");
for (size_t i = 0; i < a.size(); i++)
cout << a[i] << ' ';
cout.close();
}
void read()
{
int n;
ifstream cin("algsort.in");
cin >> n;
a.resize(n);
for (size_t i = 0; i < a.size(); i++)
cin >> a[i];
cin.close();
}
void qs(vector <int> &a)
{
if (a.size() < 100)
{
for (size_t i = 0; i < a.size(); i++)
for (size_t j = i + 1; j < a.size(); j++)
if (a[j] < a[i]) swap(a[j], a[i]);
return;
}
vector <int> x, z;
int y = 0, q = a[a.size() / 2];
for (; !a.empty(); )
{
int last = a[a.size() - 1];
if (last == q) y++;
if (last > q) z.push_back(last);
if (last < q) x.push_back(last);
a.pop_back();
}
qs(x);
qs(z);
for (size_t i = 0; i < x.size() / 2; i++)
swap(x[i], x[x.size() - 1 - i]);
for (size_t i = 0; i < z.size() / 2; i++)
swap(z[i], z[z.size() - 1 - i]);
for (; !x.empty(); )
{
int q = x[x.size() - 1];
a.push_back(q);
x.pop_back();
}
for (; y; y--)
a.push_back(q);
for (; !z.empty(); )
{
int q = z[z.size() - 1];
a.push_back(q);
z.pop_back();
}
}
int main()
{
read();
qs(a);
write();
return 0;
}