A quick sort of Java sorting algorithm

Source: Internet
Author: User

Basic Process:

    1. Set two variables i, j, when the sort begins: i=0,j=n-1;
    2. With the first array element as the key data, assign a value to key , i.e. key =a[0];
    3. Search forward from j, that is, after starting the forward search (j--), find the first value less than key a[j], will a[j] and a[i] interchange;
    4. From I start backward search, that is, start backward search (i++), find the first a[i] greater than key ], will a[i] and a[j] interchange;
    5. repeat 3rd, 4, until i=j, (3,4 step, did not find the qualifying value, that is, 3 a[j] is not less than key, 4 a[i] is not larger than the time of key change j, i value, make j=j-1, i=i+1 until it is found).

Code implementation:

 public classKuaisu { public Static voidmain (String []args) {int[] A = {12,20,5,16,15,1,30,45,23,9}; intLow = 0; intHigh = A.length-1;        Paixu (a,low,high);  for(inti = 0; i<a.length; i++) {System.out.print (a[i]+","); }          }         public Static voidPaixu (int[] a,intLowinthigh ) {        if(low<high ) {            intKey =Sort (a,low,high); Paixu (a,low,key-1); Paixu (a,key+1, high); }    }               public Static intSortint[] a,intLowinthigh ) {         intKey =a[low];  while(high>low ) {             //compare from backward to forward              while(high>low&&a[high]>=key) {//if it is larger than the key move positionhigh--; } a[low]=a[high];//not greater than, Exchange two values//from the Post-trip comparison              while(high>low&&a[low]<=key) {//if less than key move positionlow++; } a[high]=a[low];//no less than, exchange two values} a[low]=key; returnlow ; }}

Algorithm Performance Analysis:

Time complexity: fast sorting the worst time complexity is O (n^2), and the average time complexity is O (nlogn).

Space Complexity: O (n).

Stability: Direct selection is an unstable sort method because there is an interchange between nonadjacent elements in the direct selection Sort.

A quick sort of Java sorting algorithm

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.