归并排序

首先归并排序是分治法的典型例子。

将数组分成左一半,有一半,继续,直到大小为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;

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值