归并排序 java语言实现

来源:互联网 发布:oracle数据库面试题 编辑:程序博客网 时间:2024/06/12 18:25
<span style="color: rgb(255, 102, 0); font-family: 宋体; font-size: 18px;  line-height: 26px;"><strong>本博客不再更新,更多精彩内容请访问</strong></span><a target=_blank href="http://weiqianghu.github.io/" target="_blank" style="text-align: justify; text-indent: 28px; font-family: 宋体; font-size: 18px; font-weight: bold; line-height: 26px; orphans: 2; widows: 2;">我的独立博客</a>
package sort;import java.util.Random;public class MergeSort {@SuppressWarnings("unused")public boolean initTestArray(int[] testArray) {// 初始化testArrayif (testArray == null)return false;Random random = new Random();for (int i = 0; i < testArray.length; i++) {testArray[i] = random.nextInt(200);}return true;}public boolean printTestArray(int[] testArray) {// 打印testArray中的内容if (testArray == null)return false;for (int i = 0; i < testArray.length; i++) {System.out.print(testArray[i] + ",");}System.out.println();return true;}public static boolean mergeSort(int[] testArray,int left,int right){if(left<right){int mid=(left+right)/2;mergeSort(testArray,left,mid);mergeSort(testArray,mid+1,right);if(!merge(testArray,left,mid,right))return false;//for(int i=0;i<testArray.length;i++)//System.out.print(testArray[i]+",");//System.out.println();return true;}return true;}@SuppressWarnings("unused")public static boolean merge(int[] testArray,int left,int mid,int right){int i=left,j=mid+1,k=0,s=right-left+1;int[] testArray2=new int[s];if(testArray2==null){System.out.println("testArray2存储分配失败!");return false;}while(i<=mid&&j<=right)if (testArray[i] <= testArray[j])testArray2[k++]=testArray[i++];elsetestArray2[k++]=testArray[j++];while(i<=mid) testArray2[k++]=testArray[i++];while(j<=right) testArray2[k++]=testArray[j++];for(i=0;i<s;i++) {testArray[left+i]=testArray2[i];//System.out.print(testArray2[i]+",");}//System.out.println();return true;}public static void main(String args[]){int[] testArray = new int[20];MergeSort mergeSort=new MergeSort();mergeSort.initTestArray(testArray);System.out.println("排序前:");mergeSort.printTestArray(testArray);if(!MergeSort.mergeSort(testArray, 0, testArray.length-1)){System.out.println("排序出错!");return;}System.out.println("排序后:");mergeSort.printTestArray(testArray);}}


本博客不再更新,更多精彩内容请访问我的独立博客

1 0
原创粉丝点击