Data structure algorithm--2 Bubble sort, selection sort, insertion sort

  Basic sorting algorithm

        Bubble Sort

The idea is to compare adjacent elements pair by pair. When an element is larger than the adjacent element on the right, their positions are swapped. When it is smaller than the element on the right, the position remains unchanged. In the end, the largest element in the sequence, like a bubble, reaches the rightmost side.

012c2ec6bb0e46aea56ab0d18dfb1125.jpeg

 

At this time, the first round of bubble sorting ends. The position of element 9 on the far right of the array can be considered as an ordered area. There is currently one element in the ordered area.

After the second round of sorting, there are two elements in the ordered area on the right side of the sequence.

8d36f60ad52745eeb86880d49d7f3a9a.jpeg

 Since the sorting algorithm must traverse all elements in each round, the average time complexity is O(n*n)

def bubble_sort(li):  
    for i in range(len(li)-1):  # 第i趟
        for j in range(len(li)-i-1):
            if li[j]>li[j+1]:   # 降序就改一下符号
                li[j],li[j+1]=li[j+1],li[j]   

li=[random.randint(1,100) for i in range(20)]
bubble_sort(li)
print(li)

If the list does not change in a certain sorting pass, it is considered to have been sorted. At this time, if the for loop traverses, it will be a huge waste of time. We can add a flag before each traversal and add it to the code for exchanging elements. A modification flag so that the worst case scenario can be avoided.

def bubble_sort(li):
    for i in range(len(li)-1):
        exchange=False
        for j in range(len(li)-i-1):
            if li[j]>li[j+1]:
                li[j],li[j+1]=li[j+1],li[j]
                exchange=True
        print(li)  # 看每一趟的变化
        if not exchange:
            return

        selection sort

The basic idea is to traverse and filter out the smallest elements in the list in order, and finally obtain an ordered list.

def select_sort_simple(li):
    li_new=[]
    for i in range(len(li)):   # 一共需要拿i次
        min_val=min(li)
        li_new.append(min_val)
        li.remove(min_val)
    return li_new

Although this algorithm is simple, it wastes memory. We can traverse inside the list, find the smallest element and swap positions with the first element. The left ordered area will have the first element.

def select_sort(li):
    for i in range(len(li)-1):   # i趟,每次都把最小的放到前边交换
        min_loc=i   # 默认第一个最小,与后边遍历比较
        for j in range(i+1,len(li)):
            if li[j]<li[min_loc]:
                min_loc=j    # 目前的最小元素索引
        li[i],li[min_loc]=li[min_loc],li[i]
    return li

        insertion sort

469efdd8a7d14de9a1a9dfc108f5d401.png

 

^ Initially, there is only one card in hand (ordered area) (default is the first value of the element).

^ Each time, draw a card from the unordered area (the area on the right side of the list) (traverse in sequence) and insert it into the correct (by size) position in the ordered area.

def insert_sort(li):
    for i in range(1,len(li)):  # 功n-1趟,i表示摸到牌的下标
        tmp=li[i]  # 每次摸的牌
        j=i-1      # 手里最右侧的
        while j>=0 and li[j]>tmp:    # 一直往左走
            li[j+1]=li[j]    # 右移
            j-=1
        li[j+1]=tmp   # 选好位置了

It can be seen that the time complexity of insertion sort is O(n*n)

 

 

Guess you like

Origin blog.csdn.net/qq_64685283/article/details/132286539