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

    import java.util.Arrays;
    public class Main {
        public static void main(String[] args) {
            int[] a = { 6, -2, 7, 8, 3, 4, 12, 1, 0, -3, -8, 3, 4, 7 };
            System.out.println("排序之前:" + Arrays.toString(a));
            sort(a, 0, a.length - 1);
            System.out.println("排序之后:" + Arrays.toString(a));
        }
        public static int[] sort(int[] a, int low, int high) {
            int mid = (low + high) / 2;
            if (low < high) {
                sort(a, low, mid);
                sort(a, mid + 1, high);
                merge(a, low, mid, high);
            }
            return a;
        }
        public static void merge(int[] a, int low, int mid, int high) {
            int[] temp = new int[high - low + 1];
            int i = low;
            int j = mid + 1;
            int k = 0;
            // 将两数组中较小的放入temp
            while (i <= mid && j <= high) {
                if (a[i] < a[j]) {
                    temp[k] = a[i];
                    k++;
                    i++;
                } else {
                    temp[k] = a[j];
                    k++;
                    j++;
                }
            }
            // 将剩余的放入temp
            while (i <= mid) {
                temp[k] = a[i];
                k++;
                i++;
            }
            while (j <= high) {
                temp[k] = a[j];
                k++;
                j++;
            }
            // 用temp覆盖a
            for (int k2 = 0; k2 < temp.length; k2++) {
                a[k2 + low] = temp[k2];
            }
        }
    }
  • 相关阅读:
    docker基础
    paas平台
    django 多数据分库
    s3对象存储
    css
    __construct()和__initialize()
    js function
    phpstorm ftp 使用
    php
    thinkphp 笔记
  • 原文地址:https://www.cnblogs.com/hackyo/p/5891514.html
Copyright © 2011-2022 走看看