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

    一、问题描述

    对数组进行排序

    二、方法

    1. 每次对两个小数组进行排序
    2. 将整个大数组一直切分成小数组

    三、思想

    分治。

    四、code

     

     1 package algorithm;
     2 
     3 /**
     4  * Created by adrian.wu on 2019/2/14.
     5  */
     6 public class MergeSort {
     7     public void merge(int[] nums, int s, int m, int e) {
     8         if (s >= e) return;
     9 
    10         //new sorted nums
    11         int[] nsn = new int[e - s + 1];
    12 
    13         //as is the start position of s, bs is the start position of b, c is count
    14         int c = 0, as = s, bs = m + 1;
    15         while (as <= m && bs <= e) {
    16             if (nums[as] <= nums[bs]) {
    17                 nsn[c++] = nums[as++];
    18             } else {
    19                 nsn[c++] = nums[bs++];
    20             }
    21         }
    22 
    23         while (as <= m) nsn[c++] = nums[as++];
    24         while (bs <= e) nsn[c++] = nums[bs++];
    25 
    26         for (int i = s; i <= e; i++) {
    27             nums[i] = nsn[i - s];
    28         }
    29     }
    30 
    31     public void mergeSort(int[] nums, int s, int e) {
    32         //next mid
    33         if (s >= e) return;
    34         int m = (e + s) / 2;
    35         mergeSort(nums, s, m);
    36         mergeSort(nums, m + 1, e);
    37         merge(nums, s, m, e);
    38     }
    39 }
    谢谢!
  • 相关阅读:
    线程锁lock&rlock
    threading.local
    threading Event
    python中的eval 和 exec 和 execfile
    cloud-init 常见问题
    systemd
    cloud-init 的命令行
    原生js实现Promise
    js 指定位置插入html标签(可编辑div)
    js 实现复制粘贴文本过滤(保留文字和图片)
  • 原文地址:https://www.cnblogs.com/ylxn/p/10375686.html
Copyright © 2011-2022 走看看