算法之归并排序

/*归并排序*/
void mergeArray(int* a,int* temp,int left,int mid,int right)
{
	int i1 = left,i2 = mid + 1,k = 0;
	while (i1 <= mid && i2 <= right)
	{
		if (a[i1] <= a[i2])
		{
			temp[k++] = a[i1++];
		}
		else
		{
			temp[k++] = a[i2++];
		}
	}

	while (i1 <= mid)
	{
		temp[k++] = a[i1++];
	}

	while (i2 <= right)
	{
		temp[k++] = a[i2++];
	}

	for (int i = 0; i < k; i++)
	{
		a[left+i] = temp[i];
	}
}

上面代码为合并a[left,mid]和a[mid+1,right]的代码,因为归并排序是思想是先比较然后复制到另外一个临时数组,所以这里的temp起到复制存放的作用。

void mergeSort(int* a,int* temp,int left,int right)
{
	if (left < right)
	{
		int mid = (left + right)/2;
		mergeSort(a,temp,left,mid);
		mergeSort(a,temp,mid+1,right);
		mergeArray(a,temp,left,mid,right);
	}
}
上面代码为归并排序的代码。

int main()
{
	//产生length长度的100以内随机数组成的数组
	srand(time(0));
	int length;
	cout<<"Input the length of array:\n";
	cin>>length;
	int* shy_array = new int[length];
	for(int i=0;i<length;i++)
	{
		shy_array[i] = rand()/1000;
	}
	//输出数组
	printArray(shy_array,length);

	int* temp = new int[length];
	mergeSort(shy_array,temp,0,length-1);
	printArray(shy_array,length);
	delete[] temp;
}


其实代码有一个疑问,就是当 mergeSort(shy_array,temp,0,length-1);改为 mergeSort(shy_array,temp,0,length);,然后相应调整 mergeSort里面 mergeSort(a,temp,left,mid);为 mergeSort(a,temp,left,mid+1);,然后再调整mergeArray里面关于right判断为小于,这样会让程序一直卡在mergeSort(a,temp,left,mid+1);这里。这个地方需要再理解理解。
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值