package sort; import java.util.Random; public class MergeSort { @SuppressWarnings("unused") public boolean initTestArray(int[] testArray) {// 初始化testArray if (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++]; else testArray2[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); } }
版权声明:本文为博主原创文章,转载请注明出处。
原文地址:http://blog.csdn.net/weiqianghu/article/details/47205699