MergeSort.h
main.cpp
#ifndef MERGESORT_H
#define MERGESORT_H
#include <vector>
using namespace std;
class MergeSort
{
private:
int len;
vector<int>list;
vector<int>link;
public:
MergeSort(vector<int> _list, int _len);
int merge_sort(int,int);
int list_merge(int,int);
void out();
};
#endif
MergeSort.cpp
#include "MergeSort.h"
#include <iostream>
using namespace std;
MergeSort::MergeSort(vector<int> _list, int _len)
{
list.push_back(0);
link.push_back(0);
for (int i=0; i<_len; i++)
{
list.push_back(_list[i]);
link.push_back(0);
}
this->len = _len;
}
int MergeSort::list_merge(int st1, int st2)
{
int k = 0, i = st1, j = st2;
while(i && j)
if (list[i] <= list[j])
{
link[k] = i;
k = i;
i = link[i];
}
else
{
link[k] = j;
k = j;
j = link[j];
}
if (!i) link[k] = j;
else link[k] = i;
return link[0];
}
int MergeSort::merge_sort(int left, int right)
{
if (left >= right) return left;
int middle = (left + right)/2;
return list_merge(merge_sort(left, middle), merge_sort(middle+1, right));
}
void MergeSort::out()
{
int i= link[0];
int j = 0;
while(i)
{
j++;
cout << list[i] << " ";
i = link[i];
if (j%5 == 0) cout << endl;
}
cout << endl;
}
main.cpp
#include "MergeSort.h"
#include <iostream>
using namespace std;
int main()
{
vector<int> list;
int tmp;
cout << "please input num, 9999 end: " << endl;
while(cin >> tmp && tmp != 9999)
{
list.push_back(tmp);
}
MergeSort mer(list, list.size());
//mer.merge_sort(list.begin(), (list.end()-1));
mer.merge_sort(0, list.size()-1);
mer.out();
return 0;
}