Four common sorting algorithms (fast, bubble, insertion, selection sort)

# Insertion sort algorithm
def insert_sort(lst):
    for i in range(1,len(lst)): #start fragment[0:1] sorted
        # print(i)
        x = lst[i]
        j = i
        while j > 0 and lst[j-1] > x:
            lst[j] = lst[j-1] #Move the elements backward one by one in reverse order to determine the insertion position
            j -= 1
        lst[j] = x
    print(lst)

insert_sort([2,3,1,4,5])


#selection sort algorithm
def select_sort(lst):
    for i in range(len(lst) - 1): #Only need to loop len(lst) - 1 time
        k = i
        for j in range(i,len(lst)): # k is the position of the known smallest element This loop is to find out the smallest element k
            if lst[j] < lst[k]:
                k = j
        if i != k: #lst[k] is the smallest element determined, check whether it needs to be swapped
            lst[i],lst[k] = lst[k],lst[i]
    print(lst)

select_sort([3,2,4,1,5])

#Bubble (exchange) sorting algorithm
def bubble_sort(lst):
    for i in range(len(lst)):
        found = False
        for j in range(1,len(lst) - i):
            if lst[j-1] > lst[j]:
                lst[j-1],lst[j] = lst[j],lst[j-1]
                found = True
        if not found:
            break
    print(lst)

bubble_sort([30,13,25,16,47,26,19,10])

#Quicksort is one of the most influential algorithms of the 20th century
def quick_sort(lst):
    qsort_rec(lst,0,len(lst)-1)
    # print(lst)

def qsort_rec(lst,l,r):
    if l >= r:
        return #When there is no record in the segment or there is only one record and only one value, the following will not proceed
    i = l
    j = r
    pivot = lst[i] #is the initial vacancy
    while i < j: #find the final position of the pivot
        while i < j and lst[j] >= pivot: #Compare the last one with the first one and then go on
            j -= 1 #Use j to scan the records less than pivot to the left
        if i < j:
            lst[i] = lst[j]
            i += 1 # move the small record to the left
            print(lst)
        while i < j and lst[i] <= pivot:
            i += 1 #Use i to scan to the right to find records greater than pivot
        if i < j:
            lst[j] = lst[i]
            j -= 1 # move the large record to the right
            print(lst)
    lst[i] = pivot # store pivot in its final position
    # print(lst)
    qsort_rec(lst,l,i-1) #recursively process the left half of the interval
    qsort_rec(lst,i+1,r) #Recursively process the right half of the interval

# quick_sort([30,13,25,16,47,26,19,10])
quick_sort([4,3,5,1,2])
copy code

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324622382&siteId=291194637