Fast-sorting Java implementations

Source: Internet
Author: User

Quick Sort (Quicksort) is an improvement to the bubbling sort.

Quick Sort by C. A. R. Hoare was introduced in 1962. Its basic idea is: by a trip to sort the data to be sorted into two separate parts, one part of all the data is smaller than the other part of all the data, and then the two parts of the data are quickly sorted by this method, the entire sorting process can be recursive, so as to achieve the entire data into an ordered sequence. The following is a quick-sort Java implementation:
 PackageCom.newtouch.data.sort;ImportCom.newtouch.data.test.SortTestHelper; Public classQuickSort {//our algorithm does not allow any instances to be generated    PrivateQuickSort () {}//to Arr[l ... R] section for partition operations//return p, make arr[l ... P-1] < arr[p]; ARR[P+1...R] > Arr[p]    Private Static intPartition (comparable[] arr,intLintR) {Comparable v=Arr[l]; intj = l;//ARR[L+1...J] < V; arr[j+1...i) > V         for(inti = l + 1; I <= R; i++)            if(Arr[i].compareto (v) < 0) {J++;            Swap (arr, j, I);        } swap (arr, L, J); returnJ; }    Private Static voidSwap (object[] arr,intIintj) {Object T=Arr[i]; Arr[i]=Arr[j]; ARR[J]=T; }    Private Static voidSort (comparable[] arr,intLintr) {if(L >=R)return; intp =partition (ARR, L, R); Sort (arr, L, p-1); Sort (arr, p+ 1, R); }     Public Static voidsort (comparable[] arr) {intn =arr.length; Sort (arr,0, N-1); }     Public Static voidMain (string[] args) {//The Quick sort is also an O (NLOGN) complexity algorithm//1 million orders of magnitude of data can be processed easily within 1 seconds        intN = 1000000; Integer[] Arr= Sorttesthelper.generaterandomarray (N, 0, 100000); Sorttesthelper.testsort ("Com.newtouch.data.sort.QuickSort", arr); return; }}

Test Tool Class:

 Packagecom.newtouch.data.test;ImportJava.lang.reflect.Method;ImportJava.lang.Class;ImportJava.util.Random; Public classSorttesthelper {//Sorttesthelper does not allow any instances to be generated    PrivateSorttesthelper () {}//generates a random array of n elements, each of which has a random range of [RangeL, RangeR]     Public StaticInteger[] Generaterandomarray (intNintRangeL,intRangeR) {        assertRangeL <=RangeR; Integer[] Arr=NewInteger[n];  for(inti = 0; I < n; i++) Arr[i]=NewInteger (int) (Math.random () * (Ranger-rangel + 1) +RangeL)); returnarr; }    //generate an almost-ordered array//first, a fully ordered array containing [0...n-1] is generated, followed by a random exchange of swaptimes on the data//Swaptimes defines the degree of disorder of an array://Swaptimes = = 0 o'clock, the array is fully ordered//the larger the swaptimes, the more the array tends to be unordered     Public StaticInteger[] Generatenearlyorderedarray (intNintswaptimes) {integer[] arr=NewInteger[n];  for(inti = 0; I < n; i++) Arr[i]=NewInteger (i);  for(inti = 0; i < swaptimes; i++) {            intA = (int) (Math.random () *N); intB = (int) (Math.random () *N); intt =Arr[a]; Arr[a]=Arr[b]; ARR[B]=T; }        returnarr; }    //Print all the contents of an ARR array     Public Static voidPrintArray (object[] arr) { for(inti = 0; i < arr.length; i++) {System.out.print (arr[i]); System.out.print (‘ ‘);        } System.out.println (); return; }    //determine if arr array is ordered     Public Static Booleanissorted (comparable[] arr) { for(inti = 0; i < arr.length-1; i++)            if(Arr[i].compareto (arr[i + 1]) > 0)                return false; return true; }    //test sortclassname the corresponding sorting algorithm to sort the correctness of the results obtained by the ARR array and the algorithm run time     Public Static voidTestsort (String sortclassname, comparable[] arr) {//Through the reflection mechanism of Java, by sorting the class name, run the sort function        Try {            //a class object that obtains a sort function by SortclassnameClass Sortclass =Class.forName (sortclassname); //Sorting method by class object of sort functionMethod SortMethod = Sortclass.getmethod ("Sort",NewClass[]{comparable[].class}); //The sort parameter has only one, which is a comparable array of arrObject[] params =NewObject[]{arr}; LongStartTime =System.currenttimemillis (); //Call sort functionSortmethod.invoke (NULL, params); LongEndTime =System.currenttimemillis (); assertissorted (arr); System.out.println (Sortclass.getsimplename ()+ ":" + (Endtime-starttime) + "MS"); } Catch(Exception e) {e.printstacktrace (); }    }}

Test results:

Quicksort:422ms

Fast-sorting Java implementations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.