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

    /**
         * 递归找中间节点下标并分组合并
         *
         * @param data 数组
         * @param low  起始下标
         * @param high 终点下标
         */
        public static void mergerSoertByPerson(int[] data, int low, int high) {
            if (low >= high) {
                return;
            }
            int mid = low + (high - low) / 2;// 计算中间值
            mergerSoertByPerson(data, low, mid); // 排序合并前半段数组
            mergerSoertByPerson(data, mid + 1, high);// 排序合并第二段数组
            mergeByPerson(data, low, mid, high); // 合并数组
        }
    
        /**
         * 合并两段数组中的数据
         *
         * @param data 数组
         * @param low  起始下标
         * @param mid  中间下标
         * @param high 终点下标
         */
        public static void mergeByPerson(int[] data, int low, int mid, int high) {
            int i = low;
            int j = mid + 1;
            int[] temp = new int[high - low + 1];
            int k = 0;
            while (i <= mid && j <= high) {// 比较两个数组的值进行排序,并且将其移动到第三个数组中
                if (data[i] <= data[j]) {
                    temp[k++] = data[i++];
                } else {
                    temp[k++] = data[j++];
                }
            }
            // 默认设置第一段数组未未移动完
            int start = i;
            int end = mid;
            if (j <= high) { // 判断第二段数组是否是否还有未移动完的数据
                start = j;
                end = high;
            }
            // 将剩余数组中的数据一定到临时数组中
            while (start <= end) {
                temp[k++] = data[start++];
            }
            // 将排序完的数组移回原数组中
            System.arraycopy(temp, 0, data, low, high - low + 1);
    
        }
    
        public static void main(String[] args) {
    
            int data[] = {4, 5, 8, 1, 2, 3, 6, 7, 10, 9, 11};
            mergerSoertByPerson(data, 0, 10);
    
            for (int i = 0; i < data.length; i++) {
                System.out.print(data[i] + "   ");
            }
            System.out.println();
    
        }

     结果如下:

    
    
    Connected to the target VM, address: '127.0.0.1:49284', transport: 'socket'
    1   2   3   4   0   0   6   0   0   0   0   
  • 相关阅读:
    常用方法 反射常见方法
    常用方法 字符串是否是中文
    常用方法 读取 Excel的单位格 为 日期格式 的数据
    常用方法 保证数据长度相同
    常用方法 简单缓存
    P1821 [USACO07FEB]银牛派对Silver Cow Party
    P3905 道路重建
    关于宏定义
    P3512 [POI2010]PIL-Pilots
    P2398 GCD SUM
  • 原文地址:https://www.cnblogs.com/wangxiaowang/p/12402170.html
Copyright © 2011-2022 走看看