/*
* name : merge sort
* author : sangoly
* O(nlgn)
* S(n)
* date : 2014/4/15
*/
#include <iostream>
#include <cstdlib>
#include <limits>
using namespace std;
void merge(int a[], int start, int middle, int end)
{
int max = numeric_limits<int>::max();
int tempArray1[middle-start+2];//include the start to middle
int tempArray2[end-middle+1];//include the middle+1 to end
for (int i=0; i<middle-start+1; i++)
tempArray1[i] = a[start+i];
tempArray1[middle-start+1] = max;//As the soldier
for (int i=0; i<end-middle; i++)
tempArray2[i] = a[middle+1+i];
tempArray2[end-middle] = max;//As the soldier
int index1 = 0;
int index2 = 0;
for (int k=start; k<=end; k++)
a[k] = tempArray1[index1] > tempArray2[index2] ? (tempArray2[index2++]) : (tempArray1[index1++]);
}
void merge_sort(int a[], int start, int end)
{
if (start >= end)
return;
int middle = (start+end)/2;
merge_sort(a, start, middle);
merge_sort(a, middle + 1, end);
merge(a, start, middle, end);
}
int main(int argc, const char **argv) {
int a[] = {3, 41, 52, 26, 38, 57, 9, 49};
merge_sort(a, 0, 7);
for (int i=0; i<8; i++)
cout<<a[i]<<" ";
cout<<endl;
system("pause");
return 0;
}
归并排序,利用分治法的思想将一个大问题分解为形式等价的小问题的集合,递归求解。如果在插入到原数组的过程中采用插入排序的算法,也可以达到以常量组的空间复杂度完成此项任务,但这是以时间换空间的一种做法,时间性能上会有一定损耗。归并排序
最新推荐文章于 2024-12-15 17:47:59 发布