【算法基础】归并排序

1. 算法描述

把原始的数组分成若干的子数组,对每一个子数组进行排序;继续把子数组与子数组合并,合并后仍然有序,直到全部合并完成,形成有序的数组。


2. 算法实现

2.1. 合并子数组

/**
 * @param unsorted the unsorted array
 * @param first the start index for the 1st sub array
 * @param mind the end index for the 1st sub array
 * @param last the end index for the 2nd sub array
 * @param sorted the temp array 
 */
void merge(int unsorted[], int first, int mid, int last, int sorted[])
{
    int i = first; // cursor for the 1st sub array.
	int j = mid + 1; // cursor for the 2nd sub array
	int k = 0; // cursor for the temp array
	
	while (i <= mid && j <= last)
	{
	    if (unsorted[i] <= unsorted[j])
		{
		    sorted[k++] = unsorted[i++];
		}else
		{
		    sorted[k++] = unsorted[j++];
		}
	}
	
	while (i <=  mind)
	{
	    sorted[k++] = unsorted[i++];
	}
	
	while (j <= last)
	{
	    sorted[k++] = unsorted[j++];
	}
	
	for (int t = 0; t < k; t++)
	{
	    unsorted[first + t] = sorted[t];
	}
}

2.2. 递归子数组

void mergeSort(int a[], int first, int last, int temp[])
{
    if (first < last)
	{
	    int mid = (first + last) / 2;
		mergeSort(a,first, mind, temp);
		mergeSort(a,mid + 1, last, temp);
		merge(a,first,mid,last, temp);
	}
}

void Test()
{
    int a[10];
	int temp[10];
	
	mergeSort(a,0,9,temp);
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值