二路归并排序的Java实现

来源:互联网 发布:淘宝企业店注册 编辑:程序博客网 时间:2024/06/06 05:54

1、归并介绍

      归并排序是多次将两个或者两个以上的有序表合并为一个表。


   

public class MegerSort {private int[] pArrayofInts;public MegerSort(int[] pArrayofInts) {this.pArrayofInts=pArrayofInts;}public void doSort() {for(int pLength=1;pLength<pArrayofInts.length;pLength*=2)megerPass(pLength);}public void printArray(){for(int pIndex=0;pIndex<pArrayofInts.length;pIndex++){System.out.print(pArrayofInts[pIndex]+"、");}}private void megerPass(int pLength){int i=0;for(;i+2*pLength<pArrayofInts.length;i=i+2*pLength)//归并两个相邻的长度为length的子表meger(i, i+pLength-1, i+2*pLength-1);if(i+pLength-1<pArrayofInts.length){//余下两个子表,后者长度小于lengthmeger(i, i+pLength-1, pArrayofInts.length-1);}}
//如下是对2个表进行合并 pArrayofInts[low...mid]为第一段,[mid+1...high]为第二段

private void meger(int pLow,int pMid,int pHigh){int[] pTemp=new int[pHigh-pLow+1];int k=0,i=pLow,j=pMid+1;for(;k<pTemp.length&&i<=pMid&&j<=pHigh;k++){//第一段和第二段均为扫面完时循环pTemp[k]=(pArrayofInts[i]>pArrayofInts[j])?(pArrayofInts[j++]):(pArrayofInts[i++]);}for(;i<=pMid&&k<pTemp.length;k++,i++ ){//将第一段剩余的记录放入临时数组pTemp[k]=pArrayofInts[i];}for(;j<=pHigh&&k<pTemp.length;k++,j++){//将第二段剩余的记录放入临时的数组pTemp[k]=pArrayofInts[j];}for(int pTempIndex=0,pArrayIndex=pLow;pTempIndex<pTemp.length&&pArrayIndex<=pHigh;pTempIndex++,pArrayIndex++){//将临时数组赋值回pArrayofInts中pArrayofInts[pArrayIndex]=pTemp[pTempIndex];}}}



Main函数如下

public class Main {public static void main(String[] args) {int[] pArrayofInts = { 3, 5, 6, 22, 1, 0, 4 ,87,902,111};RadixSort pRadixSort = new RadixSort(pArrayofInts,1000);System.out.println("排序前:");pRadixSort.printArray();pRadixSort.doSort();System.out.println("排序后:");pRadixSort.printArray();}}



0 0
原创粉丝点击