Data Structures and Algorithms - sorting algorithm - Quick Sort

################## quick sort #######################

"""

Quicksort uses divide and conquer (Divide and conquer) a strategy to sequence the (list) 2 into smaller and larger subsequences, then sort recursively two sequences.

Steps:
1, the selection of reference values: pick a number from the column element, called a "reference" (Pivot);
2, segmentation: reordering columns, all smaller than the reference value is placed in front of the reference element, all larger than the reference value elements placed behind the reference (equal to the reference value can be any number of side).
After the end of this division, ordering the reference value has been completed;
3, the recursive sort sequences: recursively sequence will be smaller than the reference value of the element is greater than the reference value of the ordered sequence of elements.
The bottommost recursive determination condition is the size of the number of columns or a zero, at which time the number of columns apparently ordered.

"""

 

################## quick sort #######################

"""
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
The first implementation
Two cursors, left, right, the first element as a reference value, The first round, 54 as a reference value, left cursor points 26, right pointing cursor 20 Exit condition is low <= right left point to be smaller than 54, otherwise it is stopped, right point to better than 54 large, otherwise stopped, Then about exchange, continue until the exit condition is satisfied, the first round ended, Second round, the same operation continues, recursively, Recursion has been completed, the merger
"""

Code:

DEF quick_sort (alist, First, Last):
     "" " Quick Sort " "" 
    IF = First Last>:   # recursive exit conditions 
        return 
    mid_value = alist [First]
    Low = First   #
     High = Last
     the while Low <High:   # remember that it is performed alternately, two cursors overlap when the exit time is, 
        the while Low <High and [High] alist> = mid_value:
            high -= 1
        alist[low] = alist[high]  
        while low < high and alist[low] < mid_value:
            Low + =. 1 
        alist [high] = alist [Low]
     # After the loop exits, low, and high are equal, 
    alist [Low] = mid_value   # reference element into this position, 
    # of elements to the left of the reference sequences for rapid Sort 
    quick_sort (alist, First, Low - 1)   # First: Low 0 -1 original reference element on the left one 
    # on the right side of the reference sequence elements quickly sort 
    quick_sort (alist, Low + 1, Last)   # Low + 1 : The original reference element right one last: the final


if __name__ == '__main__':
    alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
    quick_sort (alist, 0, len (alist) - 1 )
     print (alist)

 

Optimal time complexity analysis

"""

A good look at the code analysis, see the logic
1, the first round of complexity is n,
2, the second round of complexity is n,
3, the end of round number? To logarithmic, logn,
Optimal time complexity: total is O (nlogn), the best case is that every value is in the middle,
The worst time complexity, O (n ^ 2)
"""

 

################## quick sort #######################

The second version # 

# This is inside Introduction to Algorithms, Comparison A method wherein different fragmentation process, only the first cycle, and to complete the trip fragment, comparison, simple code to be multiple,


#
this function is divided into two, a split return index, this index is aside greater than the reference value, aside than the reference value, # ARR = [10,. 7,. 8,. 9, 2 , 1, 5] def partition(arr, low, high): I = (Low -. 1) # minimum element index Pivot = ARR [High] # the rightmost most a split point, for J in Range (Low, High): # current element is less than or equal Pivot IF ARR [J] <= Pivot: # through each list element and a comparison reference value I = I +. 1 # first trigger is to become 0 , represents the first element is a minimum, ARR [i], ARR [J] = ARR [J], ARR [i] # as the previous step represents the first element is the minimum and therefore to replace i, # above loop exits when: i = 2 listing: [2,1,8,9,10,7,5] ARR [I +. 1], ARR [High] = ARR [High], ARR [I +. 1] # High = 5 at this time high is called a reference value i + 1 is 8, and # after the replacement, is left reference value is less than the reference value, the right side are larger than the reference value, the return (i + 1) # returns the i + 1 the so-called reference value division point of the index, # ARR [] -> sorted array # Low -> starting index # High -> End index # Quick sort function DEF QUICKSORT (arr, Low, High): IF Low < High: pi = partition(arr, low, high) quickSort(arr, low, pi - 1) quickSort(arr, pi + 1, high) arr = [10, 7, 8, 9, 2, 1, 5] n = len (arr) QUICKSORT (ARR, 0, n- -. 1 ) Print ( " sorted array: " ) for I in Range (n-): Print ( " % D " % ARR [I])

 

################## quick sort #######################

"""
First I would like to see a quick call pseudo-row row faster Code:
This code is the most critical parameter of this pivot, this code takes the first element of the sequence, then the element as a reference packet, using analytical formula that list values smaller than it is to its left, right values are larger than it. 
These sequences were then ordered recursive.
def quicksort(arr):    
    if len(arr) <= 1:        
        return arr    
    pivot = arr [len (arr) // 2 ]    
    left = [x for x in arr if x < pivot]    
    middle = [x for x in arr if x == pivot]    
    right = [x for x in arr if x > pivot]    
    return quicksort(left) + middle + quicksort(right)
print(quicksort([3, 6, 8, 19, 1, 5]))  # [1,3, 5, 6, 8, 19]
 
DEF quick_sort (B):
     "" " quicksort " "" 
    IF len (B) <2 :
         return ARR
     # Select datum, which can be easily selected, selected intermediate facilitate understanding 
    mid = arr [len (b) // 2 ]
     # define a reference value of approximately two series 
    left, right = [], []
     # removed from the original array reference value 
    b.remove (MID)
     for Item in B:
         # is greater than the reference value to the right of the discharge 
        IF Item> = MID:
            right.append(item)
        the else :
             # than the reference value placed on the left 
            left.append (Item)
     # iterative compared 
    return quick_sort (left) + [MID] + quick_sort (right)
 
 

Although short facilitate the understanding of the code, but its efficiency is very low, mainly in the following areas:
Selecting a reference packet too easily, not necessarily to the intermediate values ​​can take list
Space complexity degree, two lists analytical formula, but each time the need to traverse the entire selected sequence is compared.
If the sequence length is too small (only a few such elements), rapid discharge efficiency is not as good as the insertion sort.
Recursive affect performance, the best optimization.

"""

 

################## quick sort #######################

"""
Feature
Stability: quick drain is an unstable sort, such as are present before and after the reference value and the reference value of the same elements, the same value will be set aside, thus disrupting the relative order of the previous

Comparative: Because the comparison between the time required to sort the elements, it is more the sort

Time complexity: fast discharge time complexity of O (nlogn)

Space complexity: they need to apply sorting space, and with increasing the number of columns and the size increases, the complexity is: O (nlogn)

Merge sort and quick row: merge sort and quick exhaust introduced two priority idea is to divide and rule, but they break down and combined strategies are not the same: merge directly to the number of columns into two in the middle, 
and fast discharge is after a relatively small place big left to the right place, so merge sort will still need two columns to reorder again in the time of the merger, and fast row is a direct consolidation no longer need to sort,
so fast merge sort parallelism more efficiently, we could compare two from the diagram the difference between those. One drawback is that quick sort for small-scale datasets performance is not very good.
"""

 

################## quick sort #######################

 

################## quick sort #######################

Guess you like

Origin www.cnblogs.com/andy0816/p/12348378.html