Cod sursa(job #3133064)

Utilizator JohnnyFortaPascu Ioan JohnnyForta Data 25 mai 2023 01:13:46
Problema Sortare prin comparare Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

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

int partition(int arr[], int start, int end)
{
 
    int pivot = arr[start];
 
    int count = 0;
    for (int i = start + 1; i <= end; i++) {
        if (arr[i] <= pivot)
            count++;
    }
 
    // Giving pivot element its correct position
    int pivotIndex = start + count;
    swap(arr[pivotIndex], arr[start]);
 
    // Sorting left and right parts of the pivot element
    int i = start, j = end;
 
    while (i < pivotIndex && j > pivotIndex) {
 
        while (arr[i] <= pivot) {
            i++;
        }
 
        while (arr[j] > pivot) {
            j--;
        }
 
        if (i < pivotIndex && j > pivotIndex) {
            swap(arr[i++], arr[j--]);
        }
    }
 
    return pivotIndex;
}

void quickSort(int v[], int start, int end){
    // base case
    if (start >= end)
        return;
 
    // partitioning the array
    int p = partition(v, start, end);
 
    // Sorting the left part
    quickSort(v, start, p - 1);
 
    // Sorting the right part
    quickSort(v, p + 1, end);
}

int main(){
    ifstream in("algsort.in");
    ofstream out("algsort.out");
    int v[500000], n;
    in>>n;
    for(int i = 0; i < n; i++){
        in>>v[i];
    }
    quickSort(v, 0, n - 1);
    for(int i = 0; i < n; i++){
        out<<v[i]<<' ';
    }
    in.close();
}