CK012[分治]-递归-合并排序

代码骑士
优质创作者: 游戏开发技术领域
2023-01-12 12:50:19

一、问题描述

 

 

二、问题分析

 

三、算法设计

 

四、伪代码1

#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 

 

  

五、伪代码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:

 

...全文
32 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

5

社区成员

发帖
与我相关
我的任务
社区描述
考研408:数据结构、计算机组成原理、操作系统、计算机网络
学习方法考研面试 其他
社区管理员
  • 代码骑士
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧