排序算法---归并排序
来源:互联网 发布:淘宝 笑涵阁 猫腻 编辑:程序博客网 时间:2024/05/21 15:29
归并排序
归并排序算法可以递归的描述为:算法将数组分为两半,对每部分递归的应用归并排序。在两部分都排好序后,对他们进行归并。
归并排序算法是递归+分治的最好体现之一。
算法的大致流程,如下图:
Java代码
使用Java代码实现归并特别简单,也很容易理解.
public class MergeSort { public static void main(String[] args) { int list[] = {2, 3, 2, 5, 6, 1, -2, 3, 14, 12}; mergeSort(list); System.out.println(Arrays.toString(list)); } public static void mergeSort(int[] list) { if (list.length > 1) { //划分第一部分 int first[] = new int[list.length / 2]; System.arraycopy(list, 0, first, 0, list.length / 2);//复制 mergeSort(first);//递归 //划分第二部分 int second[] = new int[list.length - list.length / 2]; System.arraycopy(list, list.length / 2, second, 0, list.length - list.length / 2);//复制 mergeSort(second);//递归 int temp[] = merge(first, second);//归并的新数组 System.arraycopy(temp, 0, list, 0, temp.length);//复制 } } private static int[] merge(int[] first, int[] second) { //归并的新数组 int temp[] = new int[first.length + second.length]; //分别记录first,second,temp的下标 int current1 = 0, current2 = 0, current3 = 0; //在较短的数组长度内,将first与second升序合并到temp while (current1 < first.length && current2 < second.length) { if (first[current1] < second[current2]) { temp[current3++] = first[current1++]; } else { temp[current3++] = second[current2++]; } } //将较长部分剩余的添加到temp中 while (current1 < first.length) { temp[current3++] = first[current1++]; } while (current2 < second.length) { temp[current3++] = second[current2++]; } return temp; }}
复杂度
归并排序是稳定的。O(nlogn).
阅读全文
0 0
- 排序算法-归并排序
- 排序算法------归并排序
- 排序算法-归并排序
- 排序算法---归并排序
- 排序算法--归并排序
- 排序算法--归并排序
- 排序算法-归并排序
- 排序算法--归并排序
- 排序算法--归并排序
- 排序算法:归并排序
- 排序算法-归并排序
- 排序算法:归并排序
- 【排序算法】归并排序
- 排序算法--归并排序
- 排序算法-归并排序
- 排序算法--归并排序
- 排序算法:归并排序
- 【排序算法】归并排序
- 复习Java(三)简单的逻辑运算
- 【Java】用etcd做服务注册和发现
- oracle安装前系统配置查询(linux)
- CAD转PDF用迅捷CAD转换器一招搞定
- React 实现一个漂亮的 Table
- 排序算法---归并排序
- Android开发丶MaterialDesign实战のCardViewRecyclerView实现炫酷列表页
- C++设计模式之单例模式
- 在Predix搭建一个Express App
- python中的切片功能
- Android数据加密之异或加密算法
- C与指针
- K-Means++
- 关于"UnityEditor" namespace not found的问题的个人解决方案