Tag:java merge sort
Package Sort;import Java.util.random;public class MergeSort {@SuppressWarnings ("unused") Public boolean Inittestarray ( Int[] testarray) {//Initialize 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) {//print content in 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 Storage allocation failed! "); 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 ("Pre-order:"); Mergesort.printtestarray (Testarray); Mergesort.mergesort (Testarray, 0, testarray.length-1)) {System.out.println ("Error sorting! "); return;} System.out.println ("After sorting:"); Mergesort.printtestarray (Testarray);}}
Copyright NOTICE: This article is the original blogger articles, reproduced please indicate the source.
Merge sort Java language implementation