zoukankan      html  css  js  c++  java
  • mergeSort

     1 package POJ;
     2 
     3 public class Main {
     4 
     5     /**
     6      * 
     7      * MergeSort
     8      * 
     9      */
    10     public static void main(String[] args) {
    11         Main so = new Main();
    12         int[] list = { 6, 4, 2, 3, 1, 5, 10, 4, 9, 8, 11, 7 };
    13         int[] result = so.mergeSort(list);
    14         for (int a : result)
    15             System.out.println(a);
    16     }
    17 
    18     public int[] mergeSort(int[] list) {
    19         int[] helper = new int[list.length];
    20         mergeSort(list, helper, 0, list.length - 1);
    21         return list;
    22     }
    23 
    24     private void mergeSort(int[] list, int[] helper, int low, int high) {
    25         // TODO Auto-generated method stub
    26         if (low < high) {
    27             int mid = (high + low) / 2;
    28             mergeSort(list, helper, low, mid);
    29             mergeSort(list, helper, mid + 1, high);
    30             merge(list, helper, low, mid, high);
    31         }
    32     }
    33 
    34     private void merge(int[] list, int[] helper, int low, int mid, int high) {
    35         // TODO Auto-generated method stub
    36         for (int i = low; i <= high; i++) {
    37             helper[i] = list[i];
    38         }
    39         int helperLeft = low;
    40         int helperRight = mid + 1;
    41         int current = low;
    42         while (helperLeft <= mid && helperRight <= high) {
    43             if (helper[helperLeft] <= helper[helperRight]) {
    44                 list[current] = helper[helperLeft];
    45                 helperLeft++;
    46             } else {
    47                 list[current] = helper[helperRight];
    48                 helperRight++;
    49             }
    50             current++;
    51         }
    52         int remaining = mid - helperLeft;
    53         for (int i = 0; i <= remaining; i++) {
    54             list[current + i] = helper[helperLeft + i];
    55         }
    56     }
    57 }
  • 相关阅读:
    cf1100 F. Ivan and Burgers
    cf 1033 D. Divisors
    LeetCode 17. 电话号码的字母组合
    LeetCode 491. 递增的子序列
    LeetCode 459.重复的子字符串
    LeetCode 504. 七进制数
    LeetCode 3.无重复字符的最长子串
    LeetCode 16.06. 最小差
    LeetCode 77. 组合
    LeetCode 611. 有效三角形个数
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/3915632.html
Copyright © 2011-2022 走看看