归并排序
来源:互联网 发布:ubuntu恢复出厂 命令 编辑:程序博客网 时间:2024/06/15 19:24
归并排序采用分而治之(divide and conquer)的策略。
归并步骤
divide 把长度为n的输入序列分成两个长度为n/2的子序列
conquer 对这两个子序列分别采用归并排序
conbine 将两个排序好的子序列合并成一个最终的排序序列
时间复杂度
O(NlogN)
cpp实现
#include <iostream>using namespace std;template<typename T>void printArr(T *arr, int count){ int i, j; for(i=0; i<count; i++){ cout<< arr[i]<< " "; } cout<< endl; }template<typename T>void merge(T *arr, int begin, int mid, int end){ int lLen=mid-begin+1; int rLen=end-mid; T left[lLen], right[rLen]; int i,j; for(i=0; i<lLen; i++){ left[i] = arr[begin+i]; } for(j=0; j<rLen; j++){ right[j] = arr[mid+1+j]; } //merge int iL=0, iR=0, iT=0; while(iL<lLen && iR<rLen){ if(left[iL]<right[iR]){ arr[begin+iT] = left[iL++]; }else{ arr[begin+iT] = right[iR++]; } iT++; } while(iL<lLen){ arr[begin+iT] = left[iL++]; iT++; } while(iR<rLen){ arr[begin+iT] = right[iR++]; iT++; } }template<typename T>void mergeSort(T *arr, int begin, int end){ int i, j, mid; //general if(begin<end){ mid = (begin+end)/2; mergeSort(arr, begin, mid); mergeSort(arr, mid+1, end); merge(arr, begin, mid, end); }}
0 0
- 归并排序-归并排序
- 归并和归并排序
- 归并与归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 排序::归并
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- Oracle(七)--> PL/SQL 流程及要点(描述清晰 and 多图)
- http解析中的一些东西,strpbrk,strcasecmp,strncasecmp,strspn,strcspn
- LeetCode 258----Add Digits
- Xcode报错:loaded the "INY-Ym-jyd-view-lgW-0n-hka" nib but didn't get a UITableView
- 2015-09-11,随笔,数字格式化
- 归并排序
- 推荐:安卓apk的签名加密
- [leetcode]Delete Duplicate Emails
- 谈游戏服务端开发(2 )
- 编程时的零散笔记
- LDA主题模型简介
- Android 开发资源连接地址
- socket编程 及select poll epoll示例
- 【leetcod】3Sum —C++