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

    归并排序

    归并排序是一种概念上最简单的排序算法,与快速排序一样,归并排序也是基于分治法的。归并排序将待排序的元素序列分成两个长度相等的子序列,为每一个子序列排序,然后再将他们合并成一个子序列。合并两个子序列的过程也就是两路归并。

    public class MergeSort {
    public static void main(String[] args) {
    int[] arr = {1, 4, 6, 3, 2, 7, 4, 9, 20, 10};
    int[] copy = new int[10];
    mergeArr(arr, copy, 0, arr.length - 1);
    for (int i = 0; i < arr.length; i++) {
    System.out.print(arr[i] + " ");
    }
    }

    public static void mergeArr(int[] arr, int[] copy, int low, int high) {
    if (low == high)
    return;
    int mid = (low + high) / 2;
    mergeArr(arr, copy, low, mid);
    mergeArr(arr, copy, mid + 1, high);
    int i = mid;
    int j = high;
    int copyIndex = high;
    while (i >= low && j > mid) {
    if (arr[i] > arr[j]) {
    copy[copyIndex--] = arr[i--];
    } else
    copy[copyIndex--] = arr[j--];
    }
    for (; i >= low; i--)
    copy[copyIndex--] = arr[i];
    for (; j > mid; j--)
    copy[copyIndex--] = arr[j];
    for (int k = low; k <= high; k++) {
    arr[k] = copy[k];
    }
    }
    }
  • 相关阅读:
    姚班
    xxx
    1358B
    1368A
    莫烦Tensorflow 建造自己的NN
    莫烦Tensorflow 入门
    linux服务器安装Apache (Centos)
    C++ 获取Linux 服务器CPU占用率+内存空闲率(亲测绝对可以运行)
    MySQL主键从初始值自增
    基础练习 矩阵乘法
  • 原文地址:https://www.cnblogs.com/yanhowever/p/12768358.html
Copyright © 2011-2022 走看看