c++实现归并排序
来源:互联网 发布:萧山网络问政供电局 编辑:程序博客网 时间:2024/06/09 18:39
#include <iostream>#include <algorithm>#include <string>using namespace std;int arr[100];int n;//排序//归并排序 左排序右排序,归并(将两边最小的元素复制到原数组)void merge(int arr[],int l,int mid,int r);void mergeSort(int array[],int l,int r){ if(l<r){ int mid=(l+r)/2; mergeSort(array,l,mid); mergeSort(array,mid+1,r); merge(array,l,mid,r); }}void merge(int arr[],int l,int mid,int r){ int helperl=l; int helperr=mid+1; int helper[100]; for(int i=0;i<n;i++){ helper[i]=arr[i]; } int k=l; while(helperl<=mid&&helperr<=r) { if(helper[helperl]<=helper[helperr]){ arr[k]=helper[helperl]; helperl++; }else { arr[k]=helper[helperr]; helperr++; } k++; } for(int i=0;i<=mid-helperl;i++){ arr[k+i]=helper[helperl+i]; }}int main(){ cin>>n; for(int i=0;i<n;i++){ cin>>arr[i]; } mergeSort(arr,0,n-1); for(int i=0;i<n;i++){ cout<<arr[i]<<" "; } cout<<endl; return 0;}
来自程序员面试金典。
递归实现数组的归并排序。归并排序分两步,划分,归并。归并阶段创建辅助数组,将左半和右半最小的数依次写回原数组。
0 0
- 归并排序 c语言实现
- 归并排序C语言实现
- 归并排序C语言实现
- 归并排序--C语言实现
- 归并排序C语言实现
- 归并排序--c语言实现
- C语言实现归并排序
- 归并排序 --C语言实现
- 排序(6)---------归并排序(C语言实现)
- 排序算法(C实现)-------- 归并排序
- 排序算法C++&&Python实现---归并排序
- 排序算法C++&&Python实现---归并排序
- 归并排序算法 C代码实现
- 归并排序及C语言实现
- 归并排序递归实现C语言
- 归并排序非递归实现C语言
- 归并排序 MergeSort C语言实现
- C语言实现的归并排序
- 2016阿里云实习面经
- android:exported 属性详解
- HD 2048 数塔 DP(简单递推)
- C++primer第九章习题解答
- ActiveMQ 的使用
- c++实现归并排序
- cf#ecr10-C. Foe Pairs- two pointers
- 关于C++ 引用<初学写代码小记>
- C语言程序设计,实验报告程序
- 码农小汪-struts2学习8-Action中获取ActionContext,ServletActionContext,HttpServletRequest......
- ZooKeeper Watch Java API浅析getChildren
- 仿微信图片多选
- git删除未跟踪文件
- Kafka分布式消息系统