2021-03-23

对数组[3,1,2,4,5]进行递归排序,具体过程如下图所示在这里插入图片描述
代码段

#include <bits/stdc++.h>
using namespace std;
const int maxn = 100000+10;
int n = 5;
int q[5] = {3,1,2,4,5};//待排序的数组
int temp[maxn];//临时存储排序结果的数组
void merge_sort(int q[],int l,int r){
	//递归边界
	if(l >= r ) return;//单个数一定有序 不用排序了
	
	int mid = (r+l)>>1;//分割点
	//递归划分左边
	merge_sort(q,l,mid);
	//递归划分右边 注意mid已经给了左边 
	merge_sort(q,mid+1,r);
	
	//合并
	//左指针 右指针 以及 指向临时数组开端的指针
	int l_pos = l;
	int r_pos = mid+1;
	int temp_pos = l;  
	while(l_pos<=mid && r_pos <= r ){
		if(q[l_pos] <= q[r_pos])  temp[temp_pos++] = q[l_pos++];
		else temp[temp_pos++] = q[r_pos++];
	}
	//注意是while 只要条件满足就要一直执行 
	while(l_pos <= mid) temp[temp_pos++] = q[l_pos++];
	while(r_pos <= r) temp[temp_pos++] = q[r_pos++]; 
	
	//最后将temp数组当中的内容拷贝到q数组当中去
	while(l <= r){
		q[l] = temp[l];
	    l++;
	} 	
}

int main(){
	merge_sort(q,0,4);
	for(int i= 0;i<5;i++){
		cout<<q[i]<<" ";
	}
	return 0; 
}
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值