Pagini recente » Istoria paginii agm2016 | Cod sursa (job #202492) | Cod sursa (job #586064) | Cod sursa (job #1793791) | Cod sursa (job #2057776)
/// MergeSort
#include <iostream>
#include <fstream>
using namespace std;
ifstream in("algsort.in");
ofstream out("algsort.out");
const int N = 500000;
int v[N], vSorted[N];
int n;
void print(){
for(int i=0; i<n; ++i)
cout<<v[i]<<" ";
cout<<"\n";
}
void mergesort(int leftIndex, int rightIndex)
{
if(leftIndex == rightIndex)
return;
int middleIndex = (leftIndex + rightIndex) / 2;
/// Sort the two halves
mergesort(leftIndex, middleIndex);
mergesort(middleIndex+1, rightIndex);
/// Interclass the sorted halves
int length = leftIndex, firstIndex = leftIndex, secondIndex = middleIndex + 1;
while(firstIndex <= middleIndex && secondIndex <= rightIndex)
if(v[firstIndex] < v[secondIndex])
vSorted[length++] = v[firstIndex++];
else
vSorted[length++] = v[secondIndex++];
while(firstIndex <= middleIndex)
vSorted[length++] = v[firstIndex++];
while(secondIndex <= rightIndex)
vSorted[length++] = v[secondIndex++];
for(int index = leftIndex; index <= rightIndex; ++index)
v[index] = vSorted[index];
//cout<<leftIndex<<" "<<rightIndex<<"\n";
//print();
}
int main()
{
in>>n;
for(int i=0; i<n; ++i)
in>>v[i];
//print();
mergesort(0, n-1);
//print();
for(int i=0; i<n; ++i)
out<<v[i]<<" ";
return 0;
}