一.基本思想
归并排序是分治思想的典型应用
归并操作是指将两个已排序列合并成一个序列的过程
(1)申请空间,创建一个大小等于待排数组的新数组
(2)设定两个指针,初始位置分别是两个已排序列的起始位置
(3)比较两个指针指向的元素,选择相对小的元素放到合并空间(新数组)
(4)某一指针达到队尾,将另一个序列的全部元素添加至新数组
二.概览
分类:归并排序
数据结构:数组
最差时间复杂度:O(nlogn)
最优时间复杂度:O(nlogn)
平均时间复杂度:O(nlogn)
所需辅助空间:O(n)
稳定性:稳定
三.代码实现
//归并排序,分治思想的典型应用 public class Merge { public static void sort(int a[]){ int[] temp = new int[a.length]; sort(a,0,a.length-1,temp); } private static void sort(int[] a, int left, int right, int[] temp) { if(left < right){ int mid = (left+right)/2; sort(a, left, mid, temp); sort(a,mid+1,right,temp); merge(a,left,mid,right,temp); } } private static void merge(int[] a, int left, int mid, int right,int[]temp) { int i = left;//左序列指针 int j = mid+1;//右序列指针 int t = 0;//临时数组指针 while (i<=mid && j <=right){ if (a[i]<a[j]){ temp[t++] = a[i++]; }else { temp[t++] = a[j++]; } } while (i<=mid){ temp[t++] = a[i++]; } while (j<=right){ temp[t++] = a[j++]; } //将结果拷贝到原数组 t = 0; while (left <= right){ a[left++] = temp[t++]; } } public static void main(String[] args) { int a[] = {5,8,9,3,7,1,6,3}; sort(a); for (Integer i : a) { System.out.print(i+" "); } } }