Cod sursa(job #2645533)

Utilizator bogdanStaicuBogdan Staicu bogdanStaicu Data 28 august 2020 20:18:01
Problema Sortare prin comparare Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;
void interclasare(vector<int> x, vector<int> y, vector<int> v, int s, int e){
    int m=(s+e)/2;
    int i=s;
    int j=m+1;
    int k=s;
    while(i<=m && j<=e){
        if(x[i]<y[j]){
            v[k]=x[i];
            i++;
            k++;
        }
        else{
            v[k]=y[j];
            j++;
            k++;
        }
    }
    while(i<=m){
        v[k]=x[i];
        i++;
        k++;
    }
    while(j<=e){
        v[k]=y[j];
        j++;
        k++;
    }
}

void mergeSort(vector<int> v,int s, int e){
    if(s>=e)
        return;
    int m=(s+e)/2;
    vector<int> y;
    vector<int> x;
    for(int i=0;i<=m;i++)
        x[i]=v[i];
    for(int i=m+1;i<=e;i++)
        y[i]=v[i];
    mergeSort(x,s,m);
    mergeSort(y,m+1,e);
    interclasare(x, y, v, s, e);
}
int main() {
    ifstream f("algsort.in");
    int n;
    vector<int> v;
    f>>n;
    for(int i=0;i<=n-1;i++){
        int z;
        f>>z;
        v.push_back(z);
    }
//    for(int i=0;i<=n-2;i++) {
//        for (int j = i + 1; j <= n - 1; j++)
//            if (v[i] > v[j]) {
//                int aux = v[i];
//                v[i] = v[j];
//                v[j] = aux;
//            }
//    }
    mergeSort(v,0,n-1);
    f.close();
    ofstream fout("algsort.out");
    for(int i : v)
        fout<<i<<" ";
    fout.close();
    return 0;
}