java 归并排序 自己写

package endual.xier.writeagain;

public class Darray {

	private long[] theArray ;
	private int nElems ;
	
	public Darray(int max) {//构造数组
		
		this.theArray = new long[max] ; 
		this.nElems = 0 ;
	}
	
	public void insert(long value) { //插入数据
		this.theArray[this.nElems] = value ;
		this.nElems++ ;
	}
	
	public void display() { //显示数组

		for (long value :this.theArray) {
			System.out.println(value);
		}
		
	}
	
	
	public void mergeSort() {
		long[] workSpace = new long[this.nElems] ;
		recMergeSort(workSpace, 0, this.nElems-1) ;
	}

	private void recMergeSort(long[] workSpace, int lowerBound, int upperBound) {

		if (lowerBound == upperBound) {
			return ;
		}
		
		else {
			
			int mid = (lowerBound + upperBound) / 2 ; //取到一个枢纽的值
			recMergeSort(workSpace, lowerBound, mid) ;
			recMergeSort(workSpace, mid+1, upperBound) ;
			
			//排列他们
			merge(workSpace, lowerBound, mid+1, upperBound) ;
			
			
			
		}//end else 
	
		
		
	}

	private void merge(long[] workSpace, int lowPtr, //用这个数组将数组的两半归并成一个有序的数组。
			           int highPtr, int upperBound) {
		// TODO Auto-generated method stub
		
		int j = 0 ;
		int lowerBound = lowPtr ;
		int mid = highPtr - 1 ;
		
		int n = upperBound - lowerBound - 1 ; 
		
		while (lowPtr <= mid && highPtr <= upperBound) { //值到两个数组的其中一个用完了
			
			if (this.theArray[lowPtr] < this.theArray[highPtr]) {
				workSpace[j] = this.theArray[lowPtr] ; //将小的那个放入到工作的空间中去
				j++ ; //工作的空间加1
				lowPtr++ ; //最小的那个也加一
			}else if (this.theArray[lowPtr] >= this.theArray[highPtr]) {
				workSpace[j++] = this.theArray[highPtr++] ;
			}
			
		} // end while1
		
		while (lowPtr <= mid) {
			workSpace[j++] = this.theArray[lowPtr++] ; //直接复制进去  这两wihlt值能只执行一个的
		}
		
		while (highPtr <= upperBound) {
			workSpace[j++] = this.theArray[highPtr++] ;//直接复制进去   这两wihlt值能只执行一个的
		}
		
		for (j = 0; j < n; j++) {
			
			this.theArray[lowerBound+j] = workSpace[j] ; //进行复制
			
		}
		
		
		
	} //end
	
	
}

 

 

package endual.xier.writeagain;

public class MergeSortApp {

	public static void main(String[] args) {
		
		Darray da = new Darray(100) ;
		
		for (int i = 0; i < 100; i++) {
			long value = (long) (Math.random() * 10000) ;
			da.insert(value) ;
		}
		
		da.display() ;
		System.out.println("-----------------------------");
		da.mergeSort() ;
		da.display() ;
		
	}
	
	
	
}

 

 

---------------------

 

我昏了,这个居然弄不出来哪里有错误啊,天煞的。

你可能感兴趣的:(java)