归并排序java语言实现--用递归的方法
2016-04-02 14:03
615 查看
下面是排序代码:
对上面代码做简单解释:
recMergeSort函数当中lowerBou将一个数组一分为2分别进行归并,lowerBound与pperBound不相等时继续递归调用该函数,相等的时候返调用处,执行下一句函数。
下面是测试代码:
参考资料:《大话数据结构》等。
public class DArray { private long[] theArray; private int nElems; public DArray(int max){ theArray=new long[max]; nElems=0; } public void insert(long value){ theArray[nElems]=value; nElems++; } public void display(){ for(int j=0;j<nElems;j++){ System.out.print(theArray[j]+" "); } System.out.println(); } public void mergeSort(){ long[] workSpace=new long[nElems]; //开始位置为0,最大下标为总数量减1 recMergeSort(workSpace,0,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); } } 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(theArray[lowPtr]<theArray[highPtr]){ workSpace[j++]=theArray[lowPtr++]; }else{ workSpace[j++]=theArray[highPtr++]; } } //将剩余没有比较的元素直接放入放入到workSpace数组当中去 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]; } } }
对上面代码做简单解释:
recMergeSort函数当中lowerBou将一个数组一分为2分别进行归并,lowerBound与pperBound不相等时继续递归调用该函数,相等的时候返调用处,执行下一句函数。
下面是测试代码:
public class MergeSortApp { public static void main(String[] args){ int maxSize=100; DArray arr; arr=new DArray(maxSize); arr.insert(64); arr.insert(87); arr.insert(35); arr.insert(94); arr.insert(14); arr.insert(2); arr.insert(37); arr.insert(4); arr.insert(27); arr.insert(96); arr.insert(8); System.out.print("未归并排序前的序列为: "); arr.display(); System.out.print("归并排序后的序列为: "); arr.mergeSort(); arr.display(); } }运行结果如下图所示:
参考资料:《大话数据结构》等。
相关文章推荐
- (Eclipse)调试符号
- JAVA安全模型
- java作业 流水线
- SpringMvc:处理模型数据
- java反射详解
- json与Java对象转化出现net.sf.json.JSONException: There is a cycle in the hierarchy!问题
- Java中 复制文件并命名的超简洁写法
- java虚拟机 jvm 局部变量表实战
- java虚拟机 jvm 局部变量表实战
- 【细说Java】Java封箱拆箱的一些问题
- JavaWeb-10(会话技术之session&JSP)
- springMVC4(6)Unitils断言与整合测试
- Spring的jar包描述
- 使用Struts实现防止表单重复提交
- JAVA中String的常用方法?
- java单例设计模式总结
- java实现归并排序
- java 二进制数字符串转换工具类
- java 二进制数字符串转换工具类
- java线程的创建