归并排序死循环?小编十分疑惑
查看原帖
归并排序死循环?小编十分疑惑
261262
WaltVBAlston楼主2021/11/11 09:51

RT,写的归并排序,结果死循环了

code:

#include<iostream>
#include<cstdio>
using namespace std;
int n,a[100005];
void fast_sort(int l,int r){
	if(l==r){
		cout<<1<<endl;
		return;
	} 
	int mid=(l+r)/2;
	cout<<l<<" "<<r<<" "<<mid<<endl;
	fast_sort(l,mid),fast_sort(mid+1,r);
	int temp1[100005],temp2[100005];
	int maxn1=0,maxn2=0;
	for(int i=l;i<=mid;i++)
		temp1[i-l+1]=a[i],maxn1++;
	for(int i=mid+1;i<=r;i++)
		temp2[i-mid]=a[i],maxn2++;
	int x=1,y=1,now=l-1;
	while(x<=maxn1&&y<=maxn2){
		if(temp1[x]<temp2[y]){
			now++;
			a[now]=temp1[x];
			x++;
		}
		else{
			now++;
			a[now]=temp2[y];
			y++;
		}
	}
	while(x<=maxn1){
		now++;
		a[now]=temp1[x];
		x++;
	} 
	while(y<=maxn2){
		now++;
		a[now]=temp2[y];
		y++;
	}
	return;
}
int main(){
	cin>>n;
	for(int i=1;i<=n;i++)
		cin>>a[i];
	fast_sort(1,n);
	for(int i=1;i<=n;i++)
		cout<<a[i]<<" ";
	return 0;
}

据测试,在归并到[1,3]的时候就卡住了,不输出1,求大佬帮忙看下,谢谢

2021/11/11 09:51
加载中...