## Java排序算法--归并排序（MergeSort）

| |
[ 所属分类 系统（linux） | 发布者 店小二04 | 时间 20160901 | 作者 红领巾 ] 0人收藏点击收藏

/**
* Internal method that makes recursive calls
* @param a an array of Comparable items
* @param tmpArray an array to place the merged result
* @param left the left-most index of the subarray
* @param right the right-most index of the subarray
*/
private static <AnyType extends Comparable<? super AnyType>> void mergeSort(AnyType[] a,AnyType[] tmpArray,int left,int right) {
if(left<right){
int center = (left+right)/2;
mergeSort(a,tmpArray,left,center);
mergeSort(a,tmpArray,center+1,right);
merge(a,tmpArray,left,center+1,right);
}
}

/**
* Mergesort algorithm
* @param a an array of Comparable items
*/
public static <AnyType extends Comparable<? super AnyType>> void mergeSort(AnyType[] a){
AnyType[] tmpArray = (AnyType[])new Comparable[a.length];
mergeSort(a,tmpArray,0,a.length-1);
}

/**
* Internal method that merges two sorted halves of a subarray
* @param a an array of Comparable items
* @param tmpArray an array to place the merged result
* @param leftPos the left-most index of the subarray
* @param rightPos the index of the start of the second half
* @param rightEnd the right-most index of the subarray
*/
private static <AnyType extends Comparable<? super AnyType>> void merge(AnyType[] a,AnyType[] tmpArray,int leftPos,int rightPos,int rightEnd){
int leftEnd = rightPos -1;
int tmpPos = leftPos;
int numElements = rightEnd - leftPos + 1;
//main loop
while(leftPos<=leftEnd && rightPos<=rightEnd){
if(a[leftPos].compareTo(a[rightPos])<=0){
tmpArray[tmpPos++] = a[leftPos++];
}else{
tmpArray[tmpPos++] = a[rightPos++];
}
}
//Copy rest of the first array
while(leftPos<=leftEnd){
tmpArray[tmpPos++] = a[leftPos++];
}
//Copy rest of the right array
while(rightPos<=rightEnd){
tmpArray[tmpPos++] = a[rightPos++];
}
//Copy tmpArray back
for(int i=0;i<numElements;i++,rightEnd--){
a[rightEnd] = tmpArray[rightEnd];
}
}

tags: tmpArray,AnyType,lt,排序,int,param,right,rightEnd,left,Comparable,leftPos,array,rightPos

1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责；
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性，不作出任何保证或承若；
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。