Cod sursa(job #3286168)

Utilizator miruna_iliescuIliescu Miruna miruna_iliescu Data 13 martie 2025 19:33:44
Problema Sortare prin comparare Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;

void swap(int &a, int &b) {
    int temp = a;
    a = b;
    b = temp;
}

int partition(vector<int> &arr, int low, int high) {
    int pivotIndex = low + rand() % (high - low + 1);
    swap(arr[pivotIndex], arr[high]);

    int pivot = arr[high];
    int i = low - 1;

    for (int j = low; j < high; j++) {
        if (arr[j] <= pivot) {
            i++;
            swap(arr[i], arr[j]);
        }
    }
    swap(arr[i + 1], arr[high]);
    return i + 1;
}

void quicksort(vector<int> &arr, int low, int high) {
    if (low < high) {
        int pivotIndex = partition(arr, low, high);
        quicksort(arr, low, pivotIndex - 1);
        quicksort(arr, pivotIndex + 1, high);
    }
}

void printArray(const vector<int> &arr) {
    for (int num : arr)
        cout << num << " ";
    cout << "\n";
}

// int main() {
//     srand(time(0));

//     vector<int> arr = {10, 7, 8, 9, 1, 5, 3, 2, 6, 4};
//     int n = arr.size();

//     cout << "Vector nesortat: ";
//     printArray(arr);

//     quicksort(arr, 0, n - 1);

//     cout << "Vector sortat: ";
//     printArray(arr);

//     return 0;
// }

int main() {
    srand(time(0));

    ifstream fin("algsort.in");
    ofstream fout("algsort.out");

    int N;
    fin >> N;

    vector<int> arr(N);
    for (int i = 0; i < N; i++) {
        fin >> arr[i];
    }

    fin.close();

    quicksort(arr, 0, N - 1);

    for (int num : arr) {
        fout << num << " ";
    }

    fout.close();
    return 0;
}