1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
|
// https://code.google.com/p/medicine-cpp/source/browse/trunk/cpp/sorting/SortingAlgorithms.cpp
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
void swap(std::vector<int> & data, int i, int j);
void print(std::vector<int> const & data);
void Merge(std::vector<int> & data, int lowl, int highl, int lowr, int highr);
void MergeSort(std::vector<int> & data, int low, int high);
int main()
{
int a[] = {5, 6, 1, 2, 0, 8, -1, -2, 8, 0};
std::vector<int> data(a, a + sizeof(a)/sizeof(int));
MergeSort(data, 0, data.size()-1);
print(data);
return 0;
}
void swap(std::vector<int> & data, int i, int j)
{
int tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
void print(std::vector<int> const & data)
{
std::vector<int>::const_iterator iter = data.begin();
for (; iter != data.end(); ++iter)
{
cout << *iter << " ";
}
if (data.size() > 0)
{
cout << endl;
}
}
void MergeSort(std::vector<int> & data, int low, int high)
{
if (low >= high)
{
return;
}
int mid = low + (high-low)/2;
MergeSort(data, low, mid);
MergeSort(data, mid+1, high);
Merge(data, low, mid, mid+1, high);
}
void Merge(std::vector<int> & data, int lowl, int highl, int lowr, int highr)
{
int tmp_low = lowl;
std::vector<int> tmp;
while (lowl <= highl && lowr <= highr)
{
if (data[lowl] < data[lowr])
{
tmp.push_back(data[lowl++]);
}
else if (data[lowr] < data[lowl])
{
tmp.push_back(data[lowr++]);
}
else
{
tmp.push_back(data[lowl++]);
tmp.push_back(data[lowr++]);
}
}
while (lowl <= highl)
{
tmp.push_back(data[lowl++]);
}
while (lowr <= highr)
{
tmp.push_back(data[lowr++]);
}
std::vector<int>::const_iterator iter = tmp.begin();
for(; iter != tmp.end(); ++iter)
{
data[tmp_low++] = *iter;
}
}
|