归并排序
来源:互联网 发布:windows跳板机搭建 编辑:程序博客网 时间:2024/06/15 14:19
归并排序是几大排序算法中的一种,下面就来说说归并排序。
1、基本思想:归并排序是建立在归并操作上的一种有效的排序算法。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。 归并(Merge)排序法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列,每个子序列是有序的。 然后再把有序子序列合并为整体有序序列。
这段话什么意思呢?我们举个例子来说说:
有一个数组{3,5,2,10,1,7},最后的顺序要求是从左到右,从小到大,我们把这个数组从中间分开,变成两个数组为{3,5,2}和{10,1,7},我们再申请一个数组空间,然后从头比较这两个数组,把小的放进这个新申请的数组空间中,先比较3和10,3比10小,把3放进新的数组,现在新的数组为{3},继续比较5和10,5比10小,那么把5放进新的数组中,现在新的数组为{3,5},依次继续,递归执行,直到整个数组排好。
归并排序是稳定的排序方法。归并排序的时间复杂度为O(nlogn)。速度仅次于快速排序,为稳定排序算法,一般用于对总体无序,但是各子项相对有序的数列。
下面来看一段实现代码:
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */package algorithm;import java.util.Arrays;/** * 1、基本思想:是建立在归并操作上的一种有效的排序算法。该算法是采用分治法(Divide and * Conquer)的一个非常典型的应用。 归并(Merge)排序法是将两个(或两个以上)有序表合并成一个新的有序表, * 即把待排序序列分为若干个子序列,每个子序列是有序的。 然后再把有序子序列合并为整体有序序列。 * 2、适用场景:归并排序是稳定的排序方法。归并排序的时间复杂度为O(nlogn)。 * 速度仅次于快速排序,为稳定排序算法,一般用于对总体无序,但是各子项相对有序的数列。 */public class MergeSort { public void mergeSort(int... args) { if (args != null && args.length > 0) { this.recursiveSort(0, args.length - 1, args); } } private void recursiveSort(int low, int high, int... args) { if (args != null && high < args.length && low >= 0 && low < high) { int middle = (low + high) / 2; this.recursiveSort(low, middle, args); this.recursiveSort(middle + 1, high, args); this.merge(low, middle, high, args); } } private void merge(int low, int middle, int high, int... args) { if (args != null && high < args.length && low >= 0 && low <= middle && middle <= high) { int[] tempArray = new int[args.length]; int temp = low; int mid = middle + 1; int tempArrayCursor = low; while (low <= middle && mid <= high) { if (args[low] <= args[mid]) { tempArray[tempArrayCursor++] = args[low++]; } else { tempArray[tempArrayCursor++] = args[mid++]; } } while (low <= middle) { tempArray[tempArrayCursor++] = args[low++]; } while (mid <= high) { tempArray[tempArrayCursor++] = args[mid++]; } while (temp <= high) { args[temp] = tempArray[temp++]; } } } public static void main(String[] args) { int[] array = {3, 2, 5, 10, 1, 7}; MergeSort ms = new MergeSort(); ms.mergeSort(array); System.out.println(Arrays.toString(array)); }}
0 0
- 归并排序-归并排序
- 归并和归并排序
- 归并与归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 排序::归并
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 科技咨询笔记
- 九度oj 1183
- POJ 2724 Purifying Machine
- 2015-点餐系统(客户端)
- 运算符
- 归并排序
- java:用UDP协议,开发一个聊天工具代码
- HDU 1598 ( find the most comfortable road )
- 01-复杂度1. 最大子列和问题(20)
- Eclipse里添加Tomcat服务器
- leetcode[224]:Basic Calculator
- 字符串指针与char型指针数组
- KNN算法学习--python实现和java实现
- 设计模式之-----建造者模式