|
| 1 | +package cn.edu.tju.rico.sort; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | + |
| 5 | +/** |
| 6 | + * Title: 归并排序 ,概念上最为简单的排序算法,是一个递归算法 |
| 7 | + * Description:归并排序包括两个过程:归 和 并 |
| 8 | + * "归"是指将原序列分成半子序列,分别对子序列进行递归排序 |
| 9 | + * "并"是指将排好序的各子序列合并成原序列 |
| 10 | + * |
| 11 | + * 归并排序的主要问题是:需要一个与原待排序数组一样大的辅助数组空间 |
| 12 | + * |
| 13 | + * 归并排序不依赖于原始序列,因此其最好情形、平均情形和最差情形时间复杂度都一样 |
| 14 | + * 时间复杂度:最好情形O(n),平均情形O(n^2),最差情形O(n^2) |
| 15 | + * 空间复杂度:O(n) |
| 16 | + * 稳 定 性:稳定 |
| 17 | + * 内部排序(在排序过程中数据元素完全在内存) |
| 18 | + * |
| 19 | + * @author rico |
| 20 | + * @created 2017年5月20日 上午10:40:00 |
| 21 | + */ |
| 22 | +public class MergeSort { |
| 23 | + |
| 24 | + /** |
| 25 | + * @description 归并排序算法(递归算法):递去分解,归来合并 |
| 26 | + * @author rico |
| 27 | + * @created 2017年5月20日 下午4:04:52 |
| 28 | + * @param target 待排序序列 |
| 29 | + * @param left 待排序序列起始位置 |
| 30 | + * @param right 待排序序列终止位置 |
| 31 | + * @return |
| 32 | + */ |
| 33 | + public static int[] mergeSort(int[] target, int left, int right) { |
| 34 | + |
| 35 | + if(right > left){ // 递归终止条件 |
| 36 | + int mid = (left + right)/2; |
| 37 | + mergeSort(target, left, mid); // 归并排序第一个子序列 |
| 38 | + mergeSort(target, mid+1, right); // 归并排序第二个子序列 |
| 39 | + return merge(target,left,mid,right); // 合并子序列成原序列 |
| 40 | + } |
| 41 | + return target; |
| 42 | + } |
| 43 | + |
| 44 | + |
| 45 | + /** |
| 46 | + * @description 两路归并算法 |
| 47 | + * @author rico |
| 48 | + * @created 2017年5月20日 下午3:59:16 |
| 49 | + * @param target 用于存储归并结果 |
| 50 | + * @param left 第一个有序表的第一个元素所在位置 |
| 51 | + * @param mid 第一个有序表的最后一个元素所在位置 |
| 52 | + * @param right 第二个有序表的最后一个元素所在位置 |
| 53 | + * @return |
| 54 | + */ |
| 55 | + public static int[] merge(int[] target, int left, int mid, int right){ |
| 56 | + |
| 57 | + // 需要一个与原待排序数组一样大的辅助数组空间 |
| 58 | + int[] temp = Arrays.copyOf(target, target.length); |
| 59 | + |
| 60 | + // s1,s2是检查指针,index 是存放指针 |
| 61 | + int s1 = left; |
| 62 | + int s2 = mid + 1; |
| 63 | + int index = left; |
| 64 | + |
| 65 | + // 两个表都未检查完,两两比较 |
| 66 | + while(s1 <= mid && s2 <= right){ |
| 67 | + if(temp[s1] <= temp[s2]){ // 稳定性 |
| 68 | + target[index++] = temp[s1++]; |
| 69 | + }else{ |
| 70 | + target[index++] = temp[s2++]; |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + //若第一个表未检查完,复制 |
| 75 | + while(s1 <= mid){ |
| 76 | + target[index++] = temp[s1++]; |
| 77 | + } |
| 78 | + |
| 79 | + //若第二个表未检查完,复制 |
| 80 | + while(s2 <= right){ |
| 81 | + target[index++] = temp[s2++]; |
| 82 | + } |
| 83 | + return target; |
| 84 | + } |
| 85 | +} |
0 commit comments