【C++】归并排序

来源:互联网 发布:金十数据是什么 编辑:程序博客网 时间:2024/05/29 10:09
#include<iostream>using namespace std;void merge(int a[],int b[],int low,int mid,int high){   int i = low;   int j = mid+1;   int k = low;   while(i<=mid&&j<=high){       if(a[i]<=a[j]){   b[k++] = a[i++];   }   else{   b[k++] = a[j++];   }   }   while(i<=mid){   b[k++] = a[i++];   }   while(j<=high){   b[k++] = a[j++];   }   for(int i = low;i<=high;i++){a[i] = b[i];}}void mergesort(int a[],int b[],int low,int high){   if(low < high){   int mid = (low+high)/2;   mergesort(a,b,low,mid);   mergesort(a,b,mid+1,high);   merge(a,b,low,mid,high);   }}int main(){const int max = 100;int a[max],b[max];memset(a,0,100);memset(b,0,100);cout <<"元素个数: ";int c = 0;cin >> c;cout <<"元素的值: ";for(int i = 0;i<c;i++){cin >> a[i];}mergesort(a,b,0,c-1);for(int i = 0;i<c;i++){cout << b[i]<<" ";}}

0 0
原创粉丝点击