首先归并排序是分治法的典型例子。
将数组分成左一半,有一半,继续,直到大小为1,再利用回溯合并(代码量不少,但思路很简单,尽量保证1AC)。//回溯最尾端为一层一层,即收尾回溯!!比如trie树的资源释放亦是如此,请看:
trie树 -- void delete_trie(node *root) 代码!
以下是代码:
#include <iostream>
#include <cassert>
#include "vld.h"
using namespace std;
void merge_sort_recursive(int *A,int low ,int high);
void merge_array(int *A,int low ,int mid ,int high);
void merge_sort(int *A,int n);
int main()
{
int array[10] = {9,6,7,3,5,2,4,1,0,8};//自己可以更改测试用例
merge_sort(array,10);
for (int i = 0;i < 10;i++)
{
cout<<array[i]<<" ";
}
cout<<endl;
return 0;
}
void merge_sort(int *A,int n)
{
assert(A && n>0);
merge_sort_recursive(A,0,n-1);
}
void merge_sort_recursive(int *A,int low ,int high)
{
assert(A && high >= low);
if (low >= high)
{
return ;
}
int mid = (low + high)>>1;
merge_sort_recursive(A,low,mid);//分治
merge_sort_recursive(A,mid+1,high);
merge_array(A,low,mid,high);//合并
}
void merge_array(int *A,int low ,int mid ,int high)
{
assert(A && high >= low);
int *helper = new int[high - low + 1];//注意high - low + 1 为个数!
assert(helper);
int index = 0;
int left_index = low;
int right_index = mid + 1;
while(left_index <= mid && right_index <= high)//需找能比较的前面区段
{
if (A[left_index] < A[right_index])
{
helper[index] = A[left_index];
left_index++;
}
else
{
helper[index] = A[right_index];
right_index++;
}
index++;
}
while(left_index <= mid)//后面剩余的!
{
helper[index] = A[left_index];
left_index++;
index++;
}
while(right_index <= high)
{
helper[index] = A[right_index];
right_index++;
index++;
}
for (int i = 0; i < high - low + 1;i++)//注意high - low + 1 为个数
{
A[low + i] = helper[i];
}
delete []helper;
}