充分利用了把大问题转化成一个个小的子问题的思想。(由迭代或递归来实现)
/*
*************** achieve merge sorting*********************
*/
#include<iostream>
//#include<ctime>
//#include<algorithm>
using namespace std;
int tmp[15];
void merge(int data[], int start, int mid, int end)
{
int i = start, j = mid + 1, k = start, p = start;//
//if (start<mid)
{
//for ( i; i <= mid; i++)
while(i <= mid && j <= end)
{
if (data[i] <= data[j])
{
tmp[k++] = data[i++];
}
else
{
tmp[k++] = data[j++];
}
}
//若其中一路有剩余
while (i <= mid)
{
tmp[k++] = data[i++];
}
while (j <= end)
{
tmp[k++] = data[j++];
}
//将排好序的数组tmp,赋给一一对应的数组data
//for (; p <= end; p++)
while(p <= end)
{
data[p] = tmp[p];
p++;
}
}
/*
else if (data[start] > data[end])
{
swap(data[start], data[end]);
}*/
}
void mergeSort(int data[], int start, int end)
{
if (start < end)
{
int mid = (start + end) / 2;
mergeSort(data, start, mid);
mergeSort(data, mid+1, end);
merge(data, start, mid, end);
}
}
int main()
{
int b[8] = { 49,38,65,97,76,13,27,49 };
for (size_t i = 0; i < 8; i++)
{
cout << b[i] << " ";
}
cout << endl;
mergeSort(b, 0, 7);
for (size_t i = 0; i < 8; i++)
{
cout << b[i] << " ";
}
cout << endl;
int a[10] = { 7,3,2,6,9,1,2,0,6,4 };
for (size_t i = 0; i < 10; i++)
{
cout << a[i] << " ";
}
cout << endl;
mergeSort(a, 0, 9);
for (size_t i = 0; i < 10; i++)
{
cout << a[i] << " ";
}
cout << endl;
return 0;
}