对数组[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;
}