您的位置:首页 > 其它

归并排序

2015-07-26 13:59 253 查看
归并排序是几大排序算法中的一种,下面就来说说归并排序。

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));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: