Cod sursa(job #1581074)

Utilizator Ionut.popescuLiviu Rebreanu Ionut.popescu Data 26 ianuarie 2016 15:24:19
Problema Sortare prin comparare Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.69 kb
#include<stdio.h>

int v[500001];

void quick(int a[], int end);

/* Quicksort: sort the array a[2..end-1], where end < length of A - 1
 * This algorithm is from Lutz M. Wegner's paper 
 * "A generalized, one-way, stackless quicksort," 
 * BIT Numerical Mathematics 1987, Volume 27, Issue 1, pp 44-48
 */
void quick( int A[], int end )
{
    A[1] = A[end + 1] = -1;
    for (int left = 2; left <= end + 1;) {
        // A[left] is a stopper
        if (A[left] <= A[left - 1]) {
            A[left - 2] = A[left];
            left += 2;
            continue;
        }
        int i = left, j = left;
        for (int pivot = A[left]; ; A[j] = A[++i]) {
            // Find the next out of order position
            while (pivot < A[++j]) ;

            // A[j] is a stopeer, partition the current part is finished
            if (A[j] <= A[left - 1]) {
                A[i] = pivot;
                break;
            }

            // A[j] is not a stopper
            if (A[j] >= A[i - 1]) {
                A[i] = A[j]; // A[i] must be the maximum of the left part
            } else {
                A[i] = A[i - 1];
                A[i - 1] = A[j];
            }
        }
        if (left + 2 >= i) {
            A[left - 2] = A[j];
            A[j] = A[i - 1];
            left = i + 1;
        } else {
            int temp = A[i - 1];
            A[i - 1] = A[j];
            A[j] = temp;
        }
    }
}

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