当前位置:网站首页>Merge sort divide and conquer

Merge sort divide and conquer

2022-06-11 19:33:00 *c.

Divide and conquer algorithm :

1. decompose

2. government

3. Merge

#include<bits/stdc++.h>
using namespace std;
const int N=1e7+10;
void merge(int a[],int low,int high);
void mergesort(int a[],int low,int high);
int main()
{
	int a[100000];
	int i,n;cin>>n;
	for(i=0;i<n;i++)
	{
		cin>>a[i];
	}
	mergesort(a,0,n-1);
	for(i=0;i<n;i++)
	{
		cout<<a[i]<<" ";
	}
	return 0;
}

void merge(int a[],int low,int mid,int high)// government 
{
	int *b=new int[high-low+1];//b Is an auxiliary array   Using offsite sorting 
	int i=low,j=mid+1,k=0;
	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(i=low,k=0;i<=high;i++)
	{
		a[i]=b[k++];
	}
	delete[] b;// Release 
}

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);// decompose 
		merge(a,low,mid,high);// Merge backtracking 
	}
}

原网站

版权声明
本文为[*c.]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203011817253427.html