Quick sort of Python

Source: Internet
Author: User

Quick sorting (Quick sort)

The basic idea of quick sorting: to separate the pending records into two separate parts by a sort of sequencing, where some of the recorded keywords are smaller than the others, then the two parts of the records can be recursively sorted to achieve the order of the whole sequence.

1. Algorithm Description:
    • Another divide and conquer
    • Divides the array into two parts, and then sorts the parts independently
      • First select a pivot and remove it from the list (hidden at the end)
      • These elements are then divided into two parts. One is less than the pivot and the other is greater than the pivot. This kind of partition is realized by exchanging value.
      • Then the pivot is restored in the middle, and these two sections are recursively sorted quickly

Example:

Pivot: Intermediate hub (5)

Portitiom: Partitioning

Two points: two pointers (I: Left-to-right J: Left <-right)

2. Algorithm properties:
    • Not stable
    • In general, it can be proved by mathematical induction that the time complexity of fast sequencing is O (Nlog (n))
3. Code implementation
def_quick_sorted (Nums:list)list:ifLen (nums) <= 1:        returnNums Pivot=Nums[0]#Pivot the left and right side of the call Quick_sortLeft_nums = _quick_sorted ([x forXinchNums[1:]ifx < pivot])#find the left half smaller than the hubRight_nums = _quick_sorted ([x forXinchNums[1:]ifx >= Pivot])#find the right half bigger than the hub.    returnLeft_nums + [Pivot] +right_numsdefQuick_sorted (Nums:list, Reverse=false)list:"""Quick Sort"""Start=time.time () nums=_quick_sorted (nums)ifreverse:nums= Nums[::-1] t= Time.time ()-StartreturnNums, Len (nums), Tlis= [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]lis= quick_sorted (LIS, reverse=False)Print(LIS)#Output Results([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 10, 0.0)
another version
defQuick_sort (nums):#The purpose of encapsulating a layer is to make it easier for users to call    defqsort (LST, begin, end):ifBegin >=End:returnI=begin key=Lst[begin] forJinchRange (begin+1, end+1):            ifLST[J] <key:i+ = 1Lst[i], Lst[j]=Lst[j], Lst[i] lst[begin], Lst[i]=Lst[i], Lst[begin] qsort (LST, begin, I-1) qsort (lst,i+1, End) qsort (nums, 0, Len (nums)-1)

4. Basic quick sorting also has a place to optimize:1) optimize the selected Pivot_key

Each time we select Pivot_key is the first element of the subsequence, that is, Lis[low], which is a comparison of luck. When you are lucky, the value is close to the middle value of the entire sequence, the constructed tree is more balanced, the luck is poor, and the tree near the maximum or minimum position is close to the oblique tree.
In order to ensure that the Pivot_key selection is as moderate as possible, taking the values of the three special positions in the left and right of the selected sequence, the number in the middle value is Pivot_key, which is usually better than the direct use of lis[low]. In the code, add the following code in front of the original Pivot_key = Lis[low] Line:

m = low + int ((high-low)/2)if lis[low] > Lis[high]:    self.swap (Low, high)if Lis[m] > Lis[high]:    self.swap (High, m)if lis[m] > lis[low]:    Self.swap (M, low) 

If this is not good enough, you can also divide the entire sequence into 3 parts, each to find a pivot_key, and then 3 Pivot_key to do a comparison of the above to obtain the final pivot_key. At this time the Pivot_key should be very large probability is a more reliable value.

2) Reduce unnecessary exchange

The original code in the Pivot_key this record is always in the exchange, in fact, this is not necessary, it is completely possible to temporarily exist in a temporary variable, as follows:

defpartition (self, Low, high): Lis=SELF.R M= low + int ((high-low)/2)        ifLis[low] >Lis[high]: Self.swap (Low, high)ifLIS[M] >Lis[high]: Self.swap (High, m)ifLIS[M] >Lis[low]: Self.swap (m, low) Pivot_key=Lis[low]#the value of temp staging Pivot_keytemp =Pivot_key whileLow <High : whileLow < High andLis[high] >=Pivot_key:high-= 1#direct replacement, without exchanging theLis[low] =Lis[high] whileLow < High andLis[low] <=Pivot_key:low+ = 1Lis[high]=Lis[low] Lis[low]=TempreturnLow
3) Sorting when fractional groups are optimized

The recursive operation of the fast sorting algorithm can be accepted and the cost is faster when the large amount of data is sorted. But the decimal group sorting is not as fast as the direct insertion sort, that is, overkill, not necessarily faster than the chopper.
Therefore, a very simple way is based on the number of data, do a choice of which algorithm to use, the following rewrite Qsort method:

defqsort (self, Low, high):"""choose whether to use quick sort or simple insert sort depending on the length of the sequence"""    #7 is an empirical value that can be determined according to the actual situation. Max_length = 7ifHigh-Low <max_length:ifLow <High:pivot=self.partition (Low, high) self.qsort (low, pivot-1) Self.qsort (pivot+ 1, High)Else:        #the Insert_sort method is the simple insert sort algorithm we wrote earlierSelf.insert_sort ()
4) Optimize recursive operations

The recursive operation of the whole algorithm can be optimized by means of tail recursion, and the Qsort method is rewritten as follows:

defqsort (self, Low, high):"""choose whether to use quick sort or simple insert sort depending on the length of the sequence"""    #7 is an empirical value that can be determined according to the actual situation. Max_length = 7ifHigh-Low <max_length:#use a while loop instead         whileLow <High:pivot=self.partition (Low, high) self.qsort (low, pivot-1)            #using the method of tail recursionLow = pivot + 1Else:        #the Insert_sort method is the simple insert sort algorithm we wrote earlierSelf.insert_sort ()

Quick sort of Python

Related Article

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.