分治法:英文名divide and conquer,按照中国的古话就是分而治之,他是将一个大问题divide若干个小问题,再分别对这几个小问题conquer、各个击破,从而解决大问题
归并排序就是用了分治法的思想,不断的将一个数列分为前后两个数列,再进行排序
#include <iostream>
using namespace std;
///将有二个有序数列a[first...mid]和a[mid...last]合并
void MergeArray(int a[], int first, int mid, int last, int temp[])
{
int i = first, j = mid + 1;
int m = mid, n = last;
int k = 0;
while (i <= m && j <= n)
{
if(a[i] <= a[j])
temp[k++] = a[i++];
else
temp[k++] = a[j++];
}
while(i <= m)
temp[k++] = a[i++];
while(j <= n)
temp[k++] = a[j++];
//把temp[]数据装回a[]
for(i = 0; i < k; i++)
a[first + i] = temp[i];
}
void Merge(int a[], int first, int last, int temp[])
{
if (first < last)
{
int mid = (first + last) / 2;
Merge(a, first, mid, temp); //左边有序
Merge(a, mid + 1, last, temp); //右边有序
MergeArray(a, first, mid, last, temp); //合并两个有序数列
}
}
bool MergeSort(int a[], int n)
{
int *p = new int[n];
if(p == NULL)
return false;
Merge(a, 0, n - 1, p);
delete[] p;
return true;
}
int main()
{
int a[10] = {2,6,3,1,0,9,8,7,5,4};
int temp[10];
Merge(a, 0, 9, temp);
for (int i = 0; i < 10; i++)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}