Pagini recente » Borderou de evaluare (job #3367469) | Borderou de evaluare (job #3367257) | Cod sursa (job #3367255) | Cod sursa (job #3367259) | Cod sursa (job #3367258)
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;
const int NMAX = 5e5;
int v[1 + NMAX];
void quickSort(int left, int right)
{
if (left >= right) // == does not work because of the recursive calls with degenerated intervals
return;
// pivot
int pivotIdx = left + (rand() % (right - left + 1));
swap(v[pivotIdx], v[right]); // v[right] is now pivot
int idxMove = left;
for (int i = left; i <= right - 1; ++i)
{
if (v[i] < v[right])
{
swap(v[i], v[idxMove]);
++idxMove;
}
}
swap(v[right], v[idxMove]);
quickSort(left, idxMove - 1);
quickSort(idxMove + 1, right);
}
int main()
{
srand(time(nullptr));
ifstream in("algsort.in");
ofstream out("algsort.out");
ios_base::sync_with_stdio(false);
in.tie(nullptr);
out.tie(nullptr);
int n;
in >> n;
for (int i = 1; i <= n; ++i)
in >> v[i];
quickSort(1, n);
for (int i = 1; i <= n; ++i)
out << v[i] << ' ';
out << '\n';
in.close();
out.close();
return 0;
}