Cod sursa(job #2218677)

Utilizator Alex03Runcan Alexandru Alex03 Data 5 iulie 2018 14:01:13
Problema Sortare prin comparare Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 2.1 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream fin  ("algsort.in");
ofstream fout ("algsort.out");

int n,array[1000];

void merge(int array[], int left, int m, int right)
{
    int i, j, k;
    int n1 = m - left + 1; /*There we make 2 dimensions of arrays depending on where we picked the pivot*/
    int n2 =  right - m;

    /* create temporary arrays */
    int Left[n1], Right[n2];

    /* Copy data to temporary arrays L[] and R[] */
    for (i = 0; i < n1; i++)
        Left[i] = array[left + i];
    for (j = 0; j < n2; j++)
        Right[j] = array[m + 1+ j];

    /* Merge the temp arrays back into arr[l..r]*/
    i = 0; /* Initial index of first subarray */
    j = 0; /* Initial index of second subarray */
    k = left; /* Initial index of merged subarray */
    while (i < n1 && j < n2)
    {
        if (Left[i] <= Right[j])
        {
            array[k] = Left[i];
            i++;
        }
        else
        {
            array[k] = Right[j];
            j++;
        }
        k++;
    }

    /* Copy the remaining elements of Left[], if there
       are any */
    while (i < n1)
    {
        array[k] = Left[i];
        i++;
        k++;
    }

    /* Copy the remaining elements of Right[], if there
       are any */
    while (j < n2)
    {
        array[k] = Right[j];
        j++;
        k++;
    }
}

/* l is for left index and r is right index of the
   sub-array of arr to be sorted */
void mergeSort(int array[], int left, int right)
{
    if (left < right)
    {
        // Same as (left + right)/2, but avoids overflow for
        // large left and right
        int m = left+(right-left)/2; /*taking the pivot at the left of the array*/

        // Sort first and second halves
        mergeSort(array, left, m);
        mergeSort(array, m+1, right);

        merge(array, left, m, right);
    }
}

int main ()
{
    fin >> n;
    for (int i = 1; i <= n; i++)
        fin >> array[i];
    mergeSort(array , 1 , n);
    for (int i = 1; i <= n; i++)
        fout << array[i] << ' ';
    return 0;
}