Skip to content

Instantly share code, notes, and snippets.

@thinkphp
Created February 21, 2017 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thinkphp/bd5138b4891f125cbb7c555be070abbe to your computer and use it in GitHub Desktop.
Save thinkphp/bd5138b4891f125cbb7c555be070abbe to your computer and use it in GitHub Desktop.
#include <iostream>
#include <fstream>
#include <vector>
#define loop(vec) for(const auto &number : vec)
#define iter(i,begin,end) for(int i = begin; i <= end; ++i)
#define FIN "algsort.in"
#define FOUT "algsort.out"
using namespace std;
template<typename T>
void mergeSort(vector<T> &vec, T lo, T hi) {
if( lo >= hi ) return;
T m = (lo + hi)>>1;
mergeSort<T>(vec, lo, m);
mergeSort<T>(vec, m + 1, hi);
vector<T> aux;
T i = lo;
T j = m + 1;
while(i <= m && j <= hi) {
if(vec[ i ] < vec[ j ]) aux.push_back(vec[i++]);
else
aux.push_back(vec[j++]);
}
while( i <= m ) aux.push_back(vec[i++]);
while( j <= hi ) aux.push_back(vec[j++]);
T k = 0;
iter(q, lo, hi) vec[ q ] = aux[ k++ ];
}
int main() {
vector<int> vec;
ifstream fin( FIN );
ofstream fout( FOUT );
int num,
n;
fin>>n;
while( fin>>num ) vec.push_back( num );
//call the function mergeSort to sort the array
mergeSort<int>(vec, 0, vec.size()-1 );
loop( vec ) cout<<number<<" ";
return(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment