Quick sort: recursive vs. non-recursive

Source: Internet
Author: User

Fast sorting algorithm, called Fast Row, is the most practical sorting algorithm, not one, the major language standard library of the sorting function is basically based on the implementation of the fast line.

Quick-line basic idea: The basic idea of fast sorting is: The data is divided into two separate parts by a trip sort, and some of them are smaller than all the data in the other part, and then the two parts of the data are sorted quickly by this method, the whole sort process can be recursive. To achieve the entire data into an ordered sequence.

One, the use of recursive way:

defpartition (L,left,right): TMP=L[left] whileleft<Right : whileLeft<right andl[right]>=Tmp:right-=1L[left]=L[right] whileLeft<right andl[left]<=Tmp:left+=1L[right]=L[left] L[left]=tmpreturn LeftdefQuick_sort (l,left,right):ifleft<Right:mid=partition (L,left,right) quick_sort (L,left,mid-1) Quick_sort (L,mid+1, right) L=[i forIinchRange (10000)]random.shuffle (l)Print(L) quick_sort (L,0,len (L)-1)Print(l)

Second, the use of non-recursive way: the use of the idea of the stack

There are two issues to consider:

1) What is stored inside the stack?

2) What are the conditions for the end of the iteration?

-a function parameter that needs to be iterated is stored inside the stack

-The end condition is also related to the parameters that need to be iterated. For a quick sort,

The parameters of the iteration are high at the upper and lower bounds of the array, and the condition for the end of the iteration is low = = high.

defQuick_sort (L, left, right):ifLeft >=Right :returnStack=[] Stack.append (left) stack.append (right) whileStack:low=stack.pop (0) High=stack.pop (0)ifHigh-Low <=0:Continuex=L[high] I= Low-1 forJinchRange (Low, high):ifL[J] <=x:i+ = 1L[i], L[j]=L[j], L[i] l[i+ 1], l[high] = L[high], L[i + 1] Stack.extend ([Low, I, I+ 2, high])

  

Quick sort: recursive vs. non-recursive

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.