算法流程
1.选中间的值作为分界
2.递归
3.排序
C++ 代码
归并排序
void merge_sort(int l,int r){
if(l>=r) return;
int mid=l+r>>1;
merge_sort(l,mid);
merge_sort(mid+1,r);
int i=l,j=mid+1,k=0;
while(i<=mid&&j<=r){
if(q[i]<=q[j]) res[k++]=q[i++];
else res[k++]=q[j++];
}
while(i<=mid) res[k++]=q[i++];
while(j<=r) res[k++]=q[j++];
for (i = l, j = 0; i <= r; i ++, j ++ ) q[i] = res[j];
}
题解
#include<iostream>
#include<cstdio>
using namespace std;
const int N=1e5+10;
int q[N],res[N],n;
void merge_sort(int l,int r){
if(l>=r) return;
int mid=l+r>>1;
merge_sort(l,mid);
merge_sort(mid+1,r);
int i=l,j=mid+1,k=0;
while(i<=mid&&j<=r){
if(q[i]<=q[j]) res[k++]=q[i++];
else res[k++]=q[j++];
}
while(i<=mid) res[k++]=q[i++];
while(j<=r) res[k++]=q[j++];
for (i = l, j = 0; i <= r; i ++, j ++ ) q[i] = res[j];
}
int main(){
scanf("%d",&n);
for(int i=0;i<n;i++) scanf("%d",&q[i]);
merge_sort(0,n-1);
for(int i=0;i<n;i++) printf("%d ",q[i]);
return 0;
}
⭐疑问⭐
for (j = 0, i = 1; i <= r; i ++, j ++ ) q[i] = res[j]; //错误
for (i = l, j = 0; i <= r; i ++, j ++ ) q[i] = res[j]; //正确
解决:1和l没有分清楚,应该是i=l(L)