• 归并排序完整代码


    归并排序是使用递归的方法把一个数组分割成最小的单元,然后在合并成一个数组。

    在数据量较大时归并排序的效率比简单排序的效率要高,逻辑也不太复杂。下面是完整的归并排序方法类

    package com.brave.guib;
    /**
     * 归并排序完整版
     * 
     * 归并排序是将要排序的数组进行分割,直到分割为最小的单元,
     * 即一个数组中只有一个元素,然后将有序数组重组成一个数组
     * @author 小二郎,上学堂
     *
     */
    public class Guib {
    
        private int[] arr;//数组
        private int num;//计数
        
        public Guib(int max) {
            arr = new int[max];
            num = 0;
        }
        //插入方法
        public void insert(int val){
            arr[num++] = val;
        }
        //循环打印
        public void display(){
            for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i] + "
    ");
            }
        }
        //排序方法
        public void mergeSort(){
            int[] workSpace = new int[num];
            recMergeSort(workSpace, 0, num-1);
        }
        //递归调用方法
        private void recMergeSort(int[] workSpace,int lowerB,int upperB){
            
            if(lowerB == upperB) return;
            else{
                int mid = (lowerB + upperB)/2;
                recMergeSort(workSpace, lowerB, mid);
                recMergeSort(workSpace, mid + 1, upperB);
                merge(workSpace, lowerB, mid+1, upperB);
            }
            
        }
        //合并两个有序数组的方法
        private void merge(int[] workSpace,int lower,int upper,int upperB){
            int j = 0;
            int lowerB = lower;
            int mid = upper - 1;
            int n = upperB - lowerB + 1;
            
            while(lower <=mid && upper <= upperB){
                workSpace[j++] = (arr[lower] < arr[upper]?arr[lower++]:arr[upper++]);
            }
            
            while(lower <= mid)
                workSpace[j++] = arr[lower++];
            
            while(upper <= upperB)
                workSpace[j++] = arr[upper++];
            
            for ( j = 0; j < n; j++) {
                arr[lowerB + j] = workSpace[j];
            }
        }
        
    }

    希望能够通过这些代码帮助大家更好的理解归并排序

  • 相关阅读:
    OpenStack网卡桥接问题
    Linux DD添加swap分区
    OpenStack KVM嵌套虚拟化的配置
    OpenStack KVM嵌套虚拟化的配置
    received packet with own address as source address
    mysql ERROR 1040 (08004): Too many connections
    openstack以其他tenant用户创建实例
    OpenStack Controller HA (3)
    OpenStack Controller HA (2)
    OpenStack controller HA
  • 原文地址:https://www.cnblogs.com/zbrave/p/6243314.html
Copyright © 2020-2023  润新知