归并排序
来源:互联网 发布:java runnable 编辑:程序博客网 时间:2024/06/07 16:35
归并排序
适用情况:速度仅次于快排,内存少的时候使用,可以进行并行计算的时候使用。
算法思想:将要排序的序列分成两个长度相等的子序列,然后对每一个子序列进行拆分,一直到只有两个元素的两个子序列,对这两个子序列进行归并,将它们合并成一个序列,这种方法就是所说的二路归并的方法。
算法步骤:
选择相邻两个数组成一个有序序列。
选择相邻的两个有序序列组成一个有序序列。
重复第二步,直到全部组成一个有序序列。
public class MergeSort {public static void main(String[] args) {int[] data = { 0, 2, 6, 3, 4, 1, 8, 11, 9, 7 };System.out.println("排序前:" + Arrays.toString(data));sort(data, 0, data.length - 1);System.out.println("排序后:" + Arrays.toString(data));}// 二路归并private static void sort(int[] a, int low, int high) {if (low < high) {int mid = (low + high) / 2;sort(a, low, mid);sort(a, mid + 1, high);merge(a, low, mid, high);}}// 将有序的两个数组a[i]···a[m]和a[m+1]···a[n]归并到一起private static void merge(int[] a, int low, int mid, int high) {if (low == high) {return;}int[] target = new int[high - low + 1];int i, j, k = 0;// 两个数组归并,按位依次比较,小的数依次放入target中for (i = low, j = mid + 1; i <= mid && j <= high; k++) { // k为目标数组索引if (a[i] < a[j]) {target[k] = a[i++];} else {target[k] = a[j++];}}// 如果归并完后,有剩余while (i <= mid) {target[k++] = a[i++];}while (j <= high) {target[k++] = a[j++];}for (k = 0, i = low; k < target.length; k++, i++) {a[i] = target[k];}}}
算法分析:
- 时间复杂度O(nlogn),空间复杂度O(n+logn)
- 稳定
- 比较占用内存
- 效率高
阅读全文
0 0
- 归并排序-归并排序
- 归并和归并排序
- 归并与归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 排序::归并
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- KMP算法学习笔记
- PAT甲级真题及训练集(1)--1046. Shortest Distance (20)
- python 报错'gbk' codec can't encode character '\ue5d1' in position 0:
- cocos2d-x中实现对话框
- 最长公共子串
- 归并排序
- Android Studio Can't use Subversion command line client:svn
- 【jzoj3221】【HNOI2013】【游走】【高斯消元】【期望】
- 记录Android studio使用所遇到的坑
- static【C#】
- 【开发环境】芯圣烧录工具HC-PM18 4.0的使用
- android 判断摄像头是否可用(6.0以下)
- 图片浏览器
- SQL 查询某字段不为空