5
社区成员
发帖
与我相关
我的任务
分享



#include<iostream>
#include<algorithm>
using namespace std;
const int N=1100;
void inputA(int n,int *a){
for(int i=0;i<n;i++){
cin>>a[i];
}
}
void outputA(int n,int *a){
for(int i=0;i<n;i++){
cout<<a[i]<<" ";
}
}
void testA(int mid,int heigh,int *a){
cout<<"a1 :"<<endl;
for(int i=0;i<=mid;i++)
{
cout<<a[i]<<" ";
}
cout<<endl<<"a2 :"<<endl;
for(int i=mid+1;i<=heigh;i++)
{
cout<<a[i]<<" ";
}
}
void outputB(int n,int *b){
for(int i=0;i<n;i++){
cout<<b[i]<<" ";
}
}
int main(){
int n;
cin>>n;
int *a = new int[n]; //数组动态赋值
//int *a = new int[n*sizeof(int)];
inputA(n,a);
//outputA(n,a);
int low=0,heigh=n-1;//low指向数组首,heigh指向数组尾
int mid=(low+heigh)/2;//mid指中间,mid+1也就是第二个子数组的头
//此时数组a[0]-a[mid]组成了第一个子数组
//a[mid+1]-a[heigh]是第二个子数组
//testA(mid,heigh,a);
int *B = new int[n];
int i,j,k=0;
i=low;j=mid+1;
while(i<=mid&&j<=heigh){
if(a[i]<=a[j]){
B[k]=a[i];
i++;k++;
}else{
B[k]=a[j];
j++;k++;
}
}
//将剩余的元素也加入B
while(i<=mid){//前一半数组剩余
B[k]=a[i];
k++;i++;
}
while(j<=heigh){//后一半数组剩余
B[k]=a[j];
k++;j++;
}
outputB(n,B);
return 0;
}
输出示例1
输出示例2


#include<iostream>
using namespace std;
void Merge(int *a,int low,int mid,int high){
int k=0;
int i=low;
int j=mid+1;
int *b=new int[high-low+1];
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,k=0;i<=high;i++){
a[i]=b[k++];
}
}
void mergeSort(int *a,int low,int high){
if(low<high){
int mid=(low+high)/2;
mergeSort(a,low,mid);
mergeSort(a,mid+1,high);
Merge(a,low,mid,high);
}
}
int main(){
int n;
int *a=new int[n];
cout<<"请输入元素个数:"<<endl;
cin>>n;
cout<<"请输入各元素值:"<<endl;
for(int i=0;i<n;i++){
cin>>a[i];
}
//分治算法
mergeSort(a,0,n-1);
cout<<"输出排序结果为:"<<endl;
for(int i=0;i<n;i++){
cout<<a[i]<<" ";
}
return 0;
}
输出示例1:

输出示例2:
