Cod sursa(job #539741)

Utilizator sunt_emoSunt emo sunt_emo Data 23 februarie 2011 12:07:40
Problema Sortare prin comparare Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 1.03 kb
#include <stdio.h>
#include <stdlib.h>

void merge (int*,int,int*,int);

int main ()
{
    FILE *in,*out;
    int i,n,*a,m=1,k=1;
    in=fopen ("algsort.in","r");
    out=fopen ("algsort.out","w");
    fscanf (in,"%d",&n);
    while (m<n) m=m<<1;
    a=(int*) malloc (m*sizeof (int));
    for (i=0; i<n; i++) fscanf (in,"%d",a+i);
    for (i=n; i<m; i++) a[i]=-1;
    while (k<m)
    {
        for (i=0; i<m; i+=k<<1) merge (a+i,k,a+i+k,k);
        k=k<<1;
    }
    for (i=m-n; i<m; i++) fprintf (out,"%d ",a[i]); fprintf (out,"\n");
    fclose (in); fclose (out);
    return 0;
}

void merge (int *a,int n,int *b,int m)
{
    int i=0,j=0,*c=(int*) malloc ((n+m)*sizeof (int));
    while (i<n&&j<m)
    {
        if (a[i]<b[j])
        {
            c[i+j]=a[i];
            i++;
        }
        else
        {
            c[i+j]=b[j];
            j++;
        }
    }
    if (i==n) for (; j<m; j++) c[n+j]=b[j];
    else for (; i<n; i++) c[m+i]=a[i];
    for (i=0; i<n+m; i++) a[i]=c[i];
    free (c);
}