Cod sursa(job #2334639)

Utilizator mihai.constantinConstantin Mihai mihai.constantin Data 2 februarie 2019 19:44:44
Problema Sortare prin comparare Scor 60
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define dmax 500005

int v[dmax];
int N;

void swap(int *x, int *y){
    
    int temp = *x;
    *x = *y;
    *y = temp;
}

int partition(int start, int stop){
    
    int i = start - 1;
    int x = v[stop];
    
    for(int j = start; j < stop; j++){
        if(v[j] <= x){
            i++;
            swap(&v[i], &v[j]);
        }
    }
    
    swap(&v[i + 1], &v[stop]);
    return (i + 1);
}

int partition_rand(int low, int high){
    
    srand(time(0));
    int pos = rand() % (high - low) + low;
    
    swap(&v[pos], &v[high]);
    return partition(low, high);
}

void quicksort(int low, int high){
    
    if(low < high){
        int pos = partition_rand(low, high);
        quicksort(low, pos - 1);
        quicksort(pos + 1, high);
    }
}

int main()
{
    freopen("algsort.in", "r", stdin);
    freopen("algsort.out", "w", stdout);
    
    scanf("%d", &N);
    for(int i = 0; i < N; i++){
        scanf("%d", &v[i]);
    }
    
    quicksort(0, N - 1);
    
    for(int i = 0; i < N ; i++){
        printf("%d ", v[i]);
    }
    printf("\n");
    
    return 0;
}