Quick Sort is two orders of magnitude faster than insert sort
PackageTest.sort; Public classPaixu { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub int[] A = random (10000000); int[] B =A.clone (); LongL1 =System.currenttimemillis (); Insert_sort (b); LongL2 =System.currenttimemillis (); System.out.println ("Insert Sort Time:" + (l2-L1)); Check (b); int[] C =A.clone (); intStart = 0; intEnd = A.length-1; LongStartt =System.currenttimemillis (); Quick_sort (C,start,end); LongEndt =System.currenttimemillis (); System.out.println ("Quick Sort Time:" + (endt-Startt)); Check (c); } //Insert Sort Private Static int[] Insert_sort (int[] a) { //optimized insertion sorting algorithm for(inti=1;i<a.length;i++){ inttemp=A[i]; intJ; //assuming I was ordered before, I was unordered; for(j=i-1;j>=0;j--) { //the current A[j] is larger than a[i] and will a[j] move backwards if(a[j]>temp) {A[j+1]=A[j]; }Else { //the current A[i] is larger than the element before I Break; }} a[j+1]=temp; } System.out.println ("***********************"); returnA; } Private Static voidQuick_sort (int[] A,intLowintHigh ) { intStart =Low ; intEnd =High ; intKey =A[low]; while(end>start) { //compare from backward to forward while(End>start&&a[end]>=key)//If there is nothing smaller than the key value, compare next until there is a smaller swap position than the key value, and then compare it back to the previousend--; if(a[end]<=key) { inttemp =A[end]; A[end]=A[start]; A[start]=temp; } //from the post-trip comparison while(End>start&&a[start]<=key)//if there is no larger than the key value, compare next until there is a larger swap position than the key valuestart++; if(a[start]>=key) { inttemp =A[start]; A[start]=A[end]; A[end]=temp; } //at this point the first loop is finished, and the key value position is determined. The values on the left are smaller than the key values, the values on the right are larger than the key values, but the order of the two sides may be different, making the following recursive calls } //Recursive if(Start>low) Quick_sort (a,low,start-1);//left sequence. First index position to key value index-1 if(End//right sequence. Index from key value +1 to last }
Generating a random array Public Static int[] Random (intnum) { LongStart =System.currenttimemillis (); int[] A; A=New int[num]; for(inti = 0; i < num; i++) { intRand = (int) Math.Round (Math.random () *num*100000); A[i]=Rand; } LongEnd =System.currenttimemillis (); System.out.println ("Generate" +num+ "random number takes time =====>" + (End-start) + "millisecond"); returnA; }
Verify sorting resultsPrivate Static voidCheck (int[] a) {BooleanFlag =true; for(inti = 0; i < a.length-1; i++) { if(A[i+1] <A[i]) {Flag=false; Break; }} System.out.println (Flag?" Sort succeeded ":" Sort Failed "); }}
Java Quick Sort