Python implements exchange sorting

The
basic idea of bubble sorting : Assuming that the length of the list to be sorted is n, compare the values ​​of adjacent elements from back to front or from front to back. If it is in the reverse order, exchange them until the sequence is compared.
The result of each bubbling is that the smallest element in the sequence to be sorted is placed in the final position of the sequence, so that all elements can be sorted in at most n-1 passes.
Insert picture description here

def BubbleSort(A):
    le=len(A) #获取元素数目
    for i in range(le-1):#遍历le-1次
        for j in range(i,le):#每一趟冒泡,待排序元素数目都会-1
            if A[j]>A[j-1]:#逆序则交换
                A[j-1],A[j]=A[j],A[j-1]
        print(A)

tes=[23,34,243,1,28,7,56]
BubbleSort(tes)

The output is:

[34, 243, 23, 28, 7, 56, 1]
[243, 34, 28, 23, 56, 7, 1]
[243, 34, 28, 56, 23, 7, 1]
[243, 34, 56, 28, 23, 7, 1]
[243, 34, 56, 28, 23, 7, 1]
[243, 34, 56, 28, 23, 7, 1]

Space efficiency: A constant number of auxiliary units are used, so the space complexity is O(1).
Time efficiency: O(n²)
It is a stable sorting algorithm.

The
basic idea of quick sorting : Based on the divide and conquer method, any element pivot in the list to be sorted L[1...n] is taken as the benchmark, and the sorting list is divided into two independent parts L[1...k-1] through one sorting. And L[k+1…n]. Make all elements in L[1…k-1] <privot, all elements in L[k+1…n] >=privot, privot is placed in its final position L[k ], this process is a quick sort.
Then recursively repeat the above process for the two sub-tables, until each part has only one element or is empty, that is, all elements are placed in their final positions.
Insert picture description here

def quick_sort(alist, start, end):
    if start >= end:
        return
    low = start
    high = end
    mid = alist[low]
    
    while low < high:
        while low < high and mid < alist[high]:
            # 从右边开始找,如果元素小于基准,则把这个元素放到左边
            high -= 1
        alist[low] = alist[high]
        
        while low < high and mid > alist[low]:
            # 从左边开始找,如果元素大于基准,则把元素放到右边
            low += 1
        alist[high] = alist[low]
    
    # 循环退出,low==high,把基准元素放到这个位置
    alist[low] = mid
    
    # 递归调用,重新排列左边的和右边的序列
    quick_sort(alist, start, low-1)
    quick_sort(alist, low+1, end)

Space efficiency: Since the sorting algorithm is recursive, a recursive work stack is needed to store the necessary information for each layer of recursive calls, and its capacity should be consistent with the maximum depth of recursive calls. The worst case of space complexity is O(n), and the average case is O(log2 N).
Time efficiency: the worst is O(n²); the best is O(nlog2 N).
It is an unstable sorting algorithm.

Guess you like

Origin blog.csdn.net/liulanba/article/details/113993892