zoukankan      html  css  js  c++  java
  • (转)图解排序算法之归并排序

    基本思想

      归并排序(MERGE-SORT)是利用归并的思想实现的排序方法,该算法采用经典的分治(divide-and-conquer)策略(分治法将问题(divide)成一些小的问题然后递归求解,而治(conquer)的阶段则将分的阶段得到的各答案"修补"在一起,即分而治之)。

    分而治之

       可以看到这种结构很像一棵完全二叉树,本文的归并排序我们采用递归去实现(也可采用迭代的方式去实现)。阶段可以理解为就是递归拆分子序列的过程,递归深度为log2n。

    合并相邻有序子序列

      再来看看阶段,我们需要将两个已经有序的子序列合并成一个有序序列,比如上图中的最后一次合并,要将[4,5,7,8]和[1,2,3,6]两个已经有序的子序列,合并为最终序列[1,2,3,4,5,6,7,8],来看下实现步骤。

    代码实现

     1 package sortdemo;
     2 
     3 import java.util.Arrays;
     4 
     5 /**
     6  * Created by chengxiao on 2016/12/8.
     7  */
     8 public class MergeSort {
     9     public static void main(String []args){
    10         int []arr = {9,8,7,6,5,4,3,2,1};
    11         sort(arr);
    12         System.out.println(Arrays.toString(arr));
    13     }
    14     public static void sort(int []arr){
    15         int []temp = new int[arr.length];//在排序前,先建好一个长度等于原数组长度的临时数组,避免递归中频繁开辟空间
    16         sort(arr,0,arr.length-1,temp);
    17     }
    18     private static void sort(int[] arr,int left,int right,int []temp){
    19         if(left<right){
    20             int mid = (left+right)/2;
    21             sort(arr,left,mid,temp);//左边归并排序,使得左子序列有序
    22             sort(arr,mid+1,right,temp);//右边归并排序,使得右子序列有序
    23             merge(arr,left,mid,right,temp);//将两个有序子数组合并操作
    24         }
    25     }
    26     private static void merge(int[] arr,int left,int mid,int right,int[] temp){
    27         int i = left;//左序列指针
    28         int j = mid+1;//右序列指针
    29         int t = 0;//临时数组指针
    30         while (i<=mid && j<=right){
    31             if(arr[i]<=arr[j]){
    32                 temp[t++] = arr[i++];
    33             }else {
    34                 temp[t++] = arr[j++];
    35             }
    36         }
    37         while(i<=mid){//将左边剩余元素填充进temp中
    38             temp[t++] = arr[i++];
    39         }
    40         while(j<=right){//将右序列剩余元素填充进temp中
    41             temp[t++] = arr[j++];
    42         }
    43         t = 0;
    44         //将temp中的元素全部拷贝到原数组中
    45         while(left <= right){
    46             arr[left++] = temp[t++];
    47         }
    48     }
    49 }
    View Code

    执行结果

    [1, 2, 3, 4, 5, 6, 7, 8, 9]

    最后

      归并排序是稳定排序,它也是一种十分高效的排序,能利用完全二叉树特性的排序一般性能都不会太差。java中Arrays.sort()采用了一种名为TimSort的排序算法,就是归并排序的优化版本。从上文的图中可看出,每次合并操作的平均时间复杂度为O(n),而完全二叉树的深度为|log2n|。总的平均时间复杂度为O(nlogn)。而且,归并排序的最好,最坏,平均时间复杂度均为O(nlogn)。

    阅读原文  https://www.cnblogs.com/chengxiao/p/6194356.html

  • 相关阅读:
    本地启动项目后cookie跨域获取不到的处理方式
    相对URL:协议名跨域的一种处理方式
    window.open方法被浏览器拦截的处理方式
    高维前缀和
    比较函数大小
    链式前向星
    并查集
    Kruskal算法
    读书笔记 UltraGrid(4)
    读书笔记 UltraGrid(12)
  • 原文地址:https://www.cnblogs.com/GardenKeeper/p/9844914.html
Copyright © 2011-2022 走看看