当前位置:网站首页>归并排序
归并排序
2022-06-29 02:46:00 【疯疯癫癫才自由】
2——路归并排序,将序列两两分组进行排序,共有n/2组;然后再将这些组两两进行合并排序,得到n/4组,以此类推,直到只剩下一个组为止,此时这个组便是有序的。
两两分组的时候,可以用基于二分的思想进行分组。
void mergesort(int *a,int l,int r)
{
if(l>=r)
return;
else
{
int mid=l+(r-l)/2;
mergesort(a,l,mid);
mergesort(a,mid+1,r);
my_merge(a,l,mid,mid+1,r);
}
}
归并排序
void my_merge(int *a,int l1,int r1,int l2,int r2)//两个有序序列,合并为一个有序序列,tow point :将两个有序序列合并为一个有序序列,O(n)
void my_merge(int *a,int l1,int r1,int l2,int r2)//两个有序序列,合并为一个有序序列
{
int temp[r2-l1+1],index=0,i=l1,j=l2;
while(i<=r1&&j<=r2)
{
if(a[i]<a[j])
temp[index++]=a[i++];
else
temp[index++]=a[j++];
}while(i<=r1)
temp[index++]=a[i++];
while(j<=r2)
temp[index++]=a[j++];
for(i=0;i<index;++i)
a[l1+i]=temp[i];
}
/**
归并排序
tow point :将两个有序序列合并为一个有序序列,O(n)
*/
/**
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
using namespace std;
void my_merge(int *a,int l1,int r1,int l2,int r2)//两个有序序列,合并为一个有序序列
{
int temp[r2-l1+1],index=0,i=l1,j=l2;
while(i<=r1&&j<=r2)
{
if(a[i]<a[j])
temp[index++]=a[i++];
else
temp[index++]=a[j++];
}
while(i<=r1)
temp[index++]=a[i++];
while(j<=r2)
temp[index++]=a[j++];
for(i=0;i<index;++i)
a[l1+i]=temp[i];
}
void mergesort(int *a,int l,int r)
{
if(l>=r)
return;
else
{
int mid=l+(r-l)/2;
mergesort(a,l,mid);
mergesort(a,mid+1,r);
my_merge(a,l,mid,mid+1,r);
}
}
int main()
{
int n;
cin >> n;
int a[n];
for(int i=0;i<n;++i)
cin >> a[i];
mergesort(a,0,n);
for(auto b: a)
cout << b << ' ';
cout << endl;
cout << "Hello world!" << endl;
return 0;
}边栏推荐
- 对补wasm环境的一些测试
- LabVIEW jump to web page
- 深入解析 Apache BookKeeper 系列:第三篇——读取原理
- Overview of PMP project management
- String substitution
- How does sound amplify weak sounds
- PWN攻防世界Level2
- 层次分析法(AHP)
- They all talk about interviews with big factories. When I interview with small factories, I invite people to drink tea?
- What is Mipi
猜你喜欢

Analytic hierarchy process (AHP)

Overview of PMP project management

matlab习题 —— 图像绘制练习

allegro设置网络飞线以及网络颜色的方法

对补wasm环境的一些测试

PWN beginner level0

PWN attack and defense world level2

EMC、EMI、EMS的关系

"The first share of endoscope" broke into IPO two times. Last year, it lost 500million yuan. The commercialization of core products is still in doubt | IPO Express

Prepare for the Blue Bridge Cup - double pointer, BFS
随机推荐
Tuples of combined data types
Ctfhub web password default password
18. `bs对象.节点名.next_sibling` 获取兄弟节点
Three methods of time series prediction: statistical model, machine learning and recurrent neural network
HashSet storing objects and how to not store the same objects
Install mysql5.7 and change the password
mgalcu-a509
【一起上水硕系列】最简单的字幕配置
mark
LabVIEW jump to web page
Equal wealth
mark
[线性代数] 1.1 二阶与三阶行列式
[linear algebra] 1.2 total permutation and commutation
leetcode 统计放置房子的方式数
Install kibana
LinkedList学习
矩阵特征值和特征向量求解——特征值分解(EVD)
What is a thread pool?
Which securities company is the largest and safest? Which securities company has good service