Cod sursa(job #2067275)

Utilizator andytosaAndrei Tosa andytosa Data 16 noiembrie 2017 09:05:58
Problema Sortare prin comparare Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 0.91 kb
#include <stdio.h>

void mergeSort(int x, int y, int v[]){
    if(x == y) return;

    int mij = (x + y) / 2;
    mergeSort(x, mij, v);
    mergeSort(mij + 1, y, v);

    int pos1 = x;
    int pos2 = mij + 1;
    int pos = 0;
    int w[y - x + 1];
    while(pos1 <= mij && pos2 <= y)
        if(v[pos1] < v[pos2])
            w[pos++] = v[pos1++];
        else
            w[pos++] = v[pos2++];

    while(pos1 <= mij)
        w[pos++] = v[pos1++];
    while(pos2 <= y)
        w[pos++] = v[pos2++];

    int i;
    for(i = 0; i < pos; i++)
        v[x + i] = w[i];
}

int main()
{
    FILE *fin=fopen("algsort.in","r");
    FILE *fout=fopen("algsort.out","w");
    int n, v[500010], i;

    fscanf(fin, "%d", &n);
    for(i = 1; i <= n; i++)
        fscanf(fin, "%d", &v[i]);

    mergeSort(1, n, v);

    for(i = 1; i <= n; i++)
        fprintf(fout, "%d ", v[i]);
    return 0;
}