Java归并排序

package com.guge.test.recursion;

/**
 * Created by guugangzhu on 2017/5/17.
 */
public class MergeSort {
    private int[] theArray;
    private int mElems;

    public MergeSort(int max){
        theArray=new int[max];
        mElems=0;
    }

    public void insert(int value){
        theArray[mElems]=value;
        mElems++;
    }

    public void disPlay(){
        for(int content:theArray)
            System.out.print(content+"--");
    }

    public void mergeSort(){
        int[] workspace=new int[mElems];
        recMergeSort(workspace,0,mElems-1);
    }

    private void recMergeSort(int[] wordspace,int lowerBound,int upperBound){
        if(lowerBound==upperBound)
            return;
        else {
            int mid=(lowerBound+upperBound)/2;

            recMergeSort(wordspace,lowerBound,mid);
            recMergeSort(wordspace,mid+1,upperBound);
            merge(wordspace,lowerBound,mid+1,upperBound);
        }
    }

    private void merge(int[] workspace,int lowPtr,int highPtr,int upperBound){
        int j=0;
        int lowerBound=lowPtr;
        int mid=highPtr-1;
        int n=upperBound-lowerBound+1;

        while (lowPtr<=mid&&highPtr<=upperBound){
            if(theArray[lowPtr]<theArray[highPtr]){
                workspace[j++]=theArray[lowPtr++];
            }else {
                workspace[j++]=theArray[highPtr++];
            }
        }

        while (lowPtr<=mid)
            workspace[j++]=theArray[lowPtr++];

        while (highPtr<=upperBound)
            workspace[j++]=theArray[highPtr++];

        for (j = 0; j <n ; j++) {
            theArray[lowerBound+j]=workspace[j];
        }
    }

    public static void main(String[] args) {
        MergeSort mergeSort=new MergeSort(10);
        mergeSort.insert(11);
        mergeSort.insert(75);
        mergeSort.insert(63);
        mergeSort.insert(20);
        mergeSort.insert(99);
        mergeSort.insert(54);
        mergeSort.insert(31);
        mergeSort.insert(87);
        mergeSort.insert(49);
        mergeSort.insert(68);
        mergeSort.mergeSort();
        mergeSort.disPlay();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值