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(); } }
Java归并排序
最新推荐文章于 2023-12-29 12:04:23 发布