zoukankan      html  css  js  c++  java
  • 归并排序-java

    排序-归并排序

    基本思想:是指将两个或两个以上的有序表合并成一个新的有序表。

    具体步骤: 

    (1首先将整个表看成是n个有序子表,每个子表的长度为1。

    (2)然后两两归并,得到n/2个长度为2的有序子表。

    (3)然后再两两归并,直至得到一个长度为n的有序表为止。

    平均时间:O(nlogn)

    最好情况:O(nlogn)

    最坏情况:O(n2)

    辅助空间:O(n)

    稳定性:稳定

    适用场景:n比较大时

    代码实现:

     1   public static void mergeSort(int[] list) {
     2         mergeSort(list, 0, list.length - 1);
     3     }
     4 
     5     private static void mergeSort(int[] list, int left, int right) {
     6         if (left >= right)
     7             return;
     8         int center = (left + right) / 2;
     9         mergeSort(list, left, center);
    10         mergeSort(list, center + 1, right);
    11         merge(list, left, center, right);
    12     }
    13 
    14     private static void merge(int[] list, int left, int center, int right) {
    15         int[] tmpList = new int[list.length];
    16         int mid = center + 1;
    17         int k = left;
    18         int tmp = left;
    19         while (left <= center && mid <= right) {
    20             if (list[left] <= list[mid])
    21                 tmpList[k++] = list[left++];
    22             else {
    23                 tmpList[k++] = list[mid++];
    24             }
    25         }
    26 
    27         while (left <= center) {
    28             tmpList[k++] = list[left++];
    29         }
    30         while (mid <= right) {
    31             tmpList[k++] = list[mid++];
    32         }
    33         // 将临时数组中的数据保存至原数组中
    34         while (tmp <= right) {
    35             list[tmp] = tmpList[tmp++];
    36         }
    37     }
  • 相关阅读:
    Redis Cluster 剔除节点失败
    redis cluster 常用操作
    pika版本特性研究
    ueditor的集成
    pyhon类
    python之eval简述
    Python:list,tuple
    Python函数式编程学习:lambda, map, reduce, filter、sorted()、lambda、decorator
    Python中字典详解
    Python调用(运行)外部程序
  • 原文地址:https://www.cnblogs.com/yang--yang/p/4856077.html
Copyright © 2011-2022 走看看