Sorting Algorithm (6)---Quick Sort (Exchange Sort)

Direct sorting belongs to exchange sorting

Basic ideas:
1: Select 1 reference element (usually the first element or the last element), and divide the sequence to be arranged into two parts, one part is smaller than the reference element, and the other part is larger than the reference element
2: Then Repeat step 1 for these two parts of the sequence

Time complexity:
best case: O(n*logn)
worst case, degenerates to bubble sort O(n*n)

Stability: unstable

python code implementation: quick_sort.py
def swap(l, i, j):
    tmp = l[i]
    l[i] = l[j]
    l[j] = tmp

def partition(l, low, high):
    pivot = l[low] #Base element selection
    while(low != high): #Scan alternately from both ends of the array
        while(low < high and l[high] >= pivot): #Search forward from the high position, swap elements smaller than the base element to the low end
            high -= 1
        swap(l, low, high)
        while(low < high and l[low] <= pivot): #Search backwards from the low position, swap the elements larger than the base element to the high end
            low += 1
        swap(l, low, high)
    return low

def quick_sort(l, low, high):
    if low < high:
        pivokey = partition(l, low, high)
        quick_sort(l, low, pivot-1) #recursively sort the low-end array
        quick_sort(l, pivot+1, high) #Recursively sort high-end arrays

if __name__ == '__main__':
    l = [57,12,63,29,37,18,34,46,92,87]
    quick_sort(l, 0, 9)
    print('result:' + str(l))

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326678689&siteId=291194637