归并排序完美详解以及代码实现
核心思想:
-
先拆分数组,再一一合并数组 归并排序中:“归”代表的是递归的意思,即递归将数组折半的分离为单个数组,“并”是将分开的数据按照从小到大或者从大到小的顺序再放到一个数组中。时间复杂度:O(nlogn)。 图示:
代码实现:
package com.sort; /** * @author yn * @description 归并排序 */ public class MergeSort { public void mergeSort(int[] a,int left,int right){ if (left<right){ int middle = (left+right)/2; mergeSort(a, 0, middle-1); mergeSort(a, middle+1, right); merge(a,left,middle,right); } } private void merge(int[] a, int left, int middle, int right) { int[] tempArray = new int[a.length]; int rightstart = middle+1; int temp = left; int third = left; while (left<=middle&&rightstart<right){ //一个一个往新的数组里边放值,遍历被分开的两个数组; //比较两个小数组相应下标位置的数字大小,小的先放进新数组; if(a[left]<=a[rightstart]){ //比较左边第一个和右边第一个,然后把小的那一个放进到新数组;再将下标往后移动一位,继续比较; tempArray[third++] = a[left++]; }else{ tempArray[third++] = a[rightstart++]; } } //如果左边还有数据需要拷贝,把左边数组剩下的拷贝到新数组; while (left<=middle){ tempArray[third++] = a[left++]; } //如果右边还有数据需要拷贝,就把右边数组剩下的拷贝到新数组; while (rightstart<=right){ tempArray[third++] = a[rightstart++]; } while (temp<=right){ a[temp] = tempArray[temp++]; } } public static void main(String[] args){ MergeSortSelf mss = new MergeSortSelf(); int[] a = new int[]{12,3,34,5,63,63,43,2,54,64,90}; mss.mergeSort(a, 0, a.length-1); for (int num : a){ System.out.print(" " + num); } } }
输出: 2 3 5 12 34 43 63 63 54 64 90