Java enables quick sorting

Source: Internet
Author: User

For the quick sort, the class did not understand at that time, today, looked, probably can write out

Thought: To find an element as the base number, and then from both sides of the array to remove elements and base table, from the back to find a smaller number than the base number, subscript I, from the front to find a number larger than the base number, subscript J, and then two number exchange, the process of judging and guarantee i<j;

This continues the cycle, when the i=j stop, at this time the first round of operation is over, update the base number: The current base number and stop number that is subscript I book exchange, at this time can guarantee that, in addition to the new benchmark number, the subscript is the number of I is larger than the number of the front, smaller than the number behind;

Next, we use recursion to do the above two parts respectively.

The code is as follows:

int[] array;  Public voidQuickSort (intLeftintRight ) {        if(Left >Right ) {            return; }        inti,j,temp,base; I=Left ; J=Right ; Base=Array[i];  while(I! =j) {             while(array[j]>=base&&i<j) {J--; } while(array[i]<=base&&i<j) {i++; }            if(i<j) {Temp=Array[i]; Array[i]=Array[j]; ARRAY[J]=temp; }} Array[left]=Array[i]; Array[i]=Base; QuickSort (left, I-1); QuickSort (i+1, right); }
View Code

Input array: 9,8,7,6,5,4,3,2,1

Output Result: 1,2,3,4,5,6,7,8,9

Java enables quick sorting

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.