#include<iostream>
using namespace std;
const int maxn = 9;
int a[maxn] = {0,8,4,5,7,1,3,6,2};
int temp[maxn];
//排序
void merg(int l , int r , int mid){
cout<<l <<" "<<r<<endl;
int i,j,p;
i = l;
j = mid;
p = l;//指向的是temp的
while(i < mid && j <= r){
if(a[i] < a[j]){
temp[p++] = a[i++];
}else{
temp[p++] = a[j++];
}
}
while(i < mid) temp[p++] = a[i++];
while(j <= r) temp[p++] = a[j++];
p = l;
i = l;
while(p <= r){
cout<<temp[p] <<" ";
a[i++] = temp[p++];
}
cout<<endl;
cout<<"-----------"<<endl;
}
//分隔
void merge_sort(int l , int r){
if(l < r){
int mid = (l+r) / 2;
merge_sort(l,mid);
merge_sort(mid+1,r);
merg(l,r,mid+1);//将两段去排序,mid+1是有半段第一个元素
}
}
int main(){
merge_sort(1,8);
for(int i = 1 ; i <= 8 ; i++)
cout<<a[i] <<" ";
}
c++ 归并排序
最新推荐文章于 2024-09-16 17:46:36 发布