归并排序: 代码

归并排序:

代码写的比较水: 根据别人写的

想看详细的请看这里: https://blog.csdn.net/yuehailin/article/details/68961304

#include<cstdio>
using namespace std;
void GB_qsort(int a[],int first,int mid,int last,int temp[]) {
	int n=mid,m=last;
	int k=0;
	int i=first,j=mid+1;
	while(i<=n && j<=m) {
		if(a[i]<=a[j])            // 比较 如果哪个小 就把哪个先赋给temp[]
			temp[k++]=a[i++];
		else
			temp[k++]=a[j++];
	} 
	while(i<=n)              // 如果上面比较完数组还有数字,那么肯定是全部大于数组的最后一个的,   直接全部赋给数组 
		temp[k++]=a[i++];
	while(j<=m)
		temp[k++]=a[j++];
	for(i=0; i<k; i++){
		a[first+i]=temp[i];       
	}
}
void GB_sort(int a[],int first,int last,int temp[]) {

	if(first<last) {
		int mid=(first+last)/2;
		GB_sort(a,first,mid,temp);   // 递归 左边排序   first ~~ mid 
	
		GB_sort(a,mid+1,last,temp);   // 递归 右边排序  mid+1 ~~ last 
		
		GB_qsort(a,first,mid,last,temp);    // 排序 
	}
}
bool sort(int a[],int n) {
	int *p =new int [n];    // 申请空间  大小 为原来的数组 
	                   
	if(p==NULL) {            // 如果n==0 那么肯定NULL 所以false 
		return false;
	} else {
		GB_sort(a,0,n-1,p);    // n-1;  数组最后一个数字的实际下标  
		delete[] p;                  
		return true;
	}
}
int main() {
	int a[10]= {8,5,2,9,7,6,4,1,3,0};
	int i;
	sort(a,10);
	for(i=0; i<10; i++) {
		printf("%d ",a[i]);
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值