和选择排序一样,归并排序的性能不受输入数据的影响,但表现比选择排序好的多,因为始终都是O(n log n)的时间复杂度。代价是需要额外的内存空间。归并排序是建立在归并操作上的一种有效的排序算法。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。归并排序是一种稳定的排序方法。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为2-路归并。
算法描述
把长度为n的输入序列分成两个长度为n/2的子序列;
对这两个子序列分别采用归并排序;
将两个排序好的子序列合并成一个最终的排序序列。
主代码
package sort;
/**
* 归并排序
* @author potter
*
*/
public class Guibingsort {
//low代表数组的第一个数字的下标一般为0;
//mid代表数组中间点的位置
//mid+1代表从中间点分开右边数组的第一个位置的下标
//hight代表数组的最大下标值
public static void merge(int[] a,int low, int mid, int hight){
int[] temp = new int[hight - low +1];
int i = low;
int j = mid + 1;
int k = 0;
//把较小的数移入到新数组中
while (i <= mid && j <= hight) {
if (a[i] < a[j]) {
temp[k++] = a[i++];
}else {
temp[k++] = a[j++];
}
}
//把左边剩余的数组移入数组
while (i <= mid) {
temp[k++] = a[i++];
}
//把右边剩余的数组移入数组
while (j <= hight) {
temp[k++] = a[j++];
}
for(int x = 0;x < temp.length;x++){
a[x+low] = temp[x];
}
}
public static int[] sort(int[] a,int low,int hight) {
int mid = (low+hight)/2;
if (low < hight) {
sort(a, low, mid);
sort(a, mid+1, hight);
merge(a, low, mid, hight);
}
return a;
}
}
随机生成数组
package utilsort;
import java.util.Random;
/**
* 随机生成数组
* @author Administrator
*
*/
public class UtilsSort {
static Random r = new Random();
//length代表数组长度
//min代表可以随机生成数组的最小值
//max代表可以随机生成数组的最大值
public static int[] creat(int length,int min,int max){
if (min > max) {
int temp = min;
min = max;
max = temp;
}
int arr[] = new int[length];
for (int i = 0; i < length; i++) {
int nextInt = r.nextInt(max);
arr[i] = nextInt + min ;
}
return arr;
}
}
遍历输出类
package utilsort;
public class PrintUtils {
public static void printarr(int[] arr){
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
}