Common sorting algorithms (bubble sort, selection sort, insertion sort, quick sort)

1. Bubble Sort

Bubble sort (English: Bubble Sort) is a simple sorting algorithm. It repeatedly traverse the number of columns to be sorted, a comparison of two elements, if they put them in the wrong order switching over.

"""
冒泡排序
"""
# 第一轮,依次取索引0和1、1和2,...,n-2和n-1两两比较,小的在前大的在后。一轮结束最大的在最后
# 第二轮,依次取索引0和1、1和2,...,n-3和n-2两两比较,小的在前大的在后。二轮结束次大的在倒数第二
# 第n-1轮,取索引0和1比,最小值放最前面


def bubble_sort(li):
    n = len(li)
    for i in range(0, n-1):
        for j in range(0, n-1-i):  # 每轮结束,已排序列增加,未排序列减少
            if li[j] > li[j+1]:
                li[j], li[j+1] = li[j+1], li[j]


li = [55, -2, 43, 91, 22, 1, 44, 90, 34]
bubble_sort(li)
print(li)

time complexity

  • Optimal time complexity: O (n) (represented traversal time that no elements can be exchanged, sorting ends.)
  • The worst time complexity: O (n2)
  • Stability: Stable

2. Select Sort

Selection Sort (Selection sort) is a straightforward sorting algorithm. It works as follows. First, find the smallest sequence of unsorted (large) element, the starting position is stored in the sorted sequence, and then continue to find the minimum (large) element from the remaining elements of unsorted and sorted into the end of the sequence. And so on, until all the elements are sorted.

"""
选择排序
"""
# 第一轮,假设min_index=0,从索引1开始往后依次取值与索引0处比较,小于索引0,则最小值索引位置设置为当前索引。
# 每轮比较结束,判断min_index是否改变,改变则交换这一轮中实际的min_index和初始的min_index的值。最小值在最前面。

# 第二轮,假设min_index=1,从索引2开始依次往后取值与1处比较,找到次小值。交换次小值与本轮初始min_index=1的位置

# 重复n-1轮。


def select_sort(li):
    n = len(li)

    for i in range(0, n-1):
        min_index = i

        for j in range(i+1, n):
            if li[j] < li[min_index]:
                min_index = j
        if min_index != i:
            li[min_index], li[i] = li[i], li[min_index]


li1 = [55, -2, 43, 91, 22, 1, 44, 90, 34]
select_sort(li1)
print(li1)

time complexity

  • The optimal time complexity: O (n2)
  • The worst time complexity: O (n2)
  • Stability: Unstable (ascending consider each selection largest case)

3. Insertion Sort

Insertion sort (English: Insertion Sort) is a simple and intuitive sorting algorithm. It works by constructing an ordered sequence, for unsorted data, scanning in the sorted sequence from back to front, and find the corresponding insertion positions. Insertion sort in the realization, from back to front in the scanning process, the need to repeatedly ordered elements gradually move back position, to provide space for the insertion of new elements.

"""
插入排序
"""
# 第一轮,假设索引0有序,则取索引1与0比较,大于不交换进行下一轮,小于则交换索引0和1

# 第二轮,假设索引0和1有序,则取索引2依次与索引1和索引0比,小于交换,大于进入下一轮

# 第n-1轮,假设0,1,...,n-2有序,取索引n-1依次与n-2,n-3,...,1,0比较,小于交换,大于结束


def insert_sort(li):
    n = len(li)
    for i in range(0, n-1):    # 循环比较n-1轮
        for j in range(i+1, 0, -1):
            if li[j] < li[j-1]:
                li[j], li[j-1] = li[j-1], li[j]
            else:
                break


li1 = [55, -2, 43, 91, 22, 1, 44, 90, 34]
insert_sort(li1)
print(li1)

time complexity

  • Optimal time complexity: O (n) (in ascending order, in ascending sequence has state)
  • The worst time complexity: O (n2)
  • Stability: Stable

4. Quick Sort

Quick Sort (English: Quicksort), also known as the exchange Sort division (partition-exchange sort), a trip by ordering the data to be sorted into separate two parts, one part of all of the data than the other part of all of the data to be smaller then the two parts of the data in this way were quick sort, to sort the entire process can be recursively, in order to achieve the whole data into an ordered sequence.

Steps:

Pick out the number of columns in an element, called a "reference" (Pivot),
reordering columns, all of the elements placed in front of the reference small than the reference value, the reference value is larger than all of the elements placed at the back of the reference (the same number of It can be either side). After the end of the partition, the reference is in the middle of the number of columns. This is called the partition (partition) operation.
Number of sub recursively (recursive This) than the reference value the number of columns and the sub-element is greater than the reference value of the element column.
The bottom case of recursion, the size is the number of columns is zero or one, that is, always has been sorted well. While it has been recursion, but this algorithm will always end, because in each iteration (iteration), which will at least one element placed in its final position to go.

"""
快速排序
"""


# 先假设索引0是中间值,mid = li[0],记录下来这个中间值mid
# 创建两个游标left=0,right=列表长度-1
# 取最后面的right与mid进行比较,大于mid,则right向左移,直到小于mid,这个时候,设置li[left]=li[right],
# 此时right停止移动,转而left开始比较。最后一个的元素位置空出来可以复制操作

# 即比较li[left]和mid,如果小于mid,则left向右移动,如果大于mid,则设置li[right]=li[left]
# 此时left停止移动,right开始移动,left位置又空出来允许赋值操作

# 这样一轮比较之后,left和right相遇,left=right,可以li[left]=mid,那么mid左侧都是<mid的值,右侧均>mid

# 接着left_list = li[:mid],右侧列表:right_list = li[mid:],再对其进行递归快速排序
def quick_sort(alist, start, end):
    """快速排序"""

    # 递归的退出条件
    if start >= end:
        return

    # 设定起始元素为要寻找位置的基准元素
    mid = alist[start]

    # low为序列左边的由左向右移动的游标
    low = start

    # high为序列右边的由右向左移动的游标
    high = end

    while low < high:
        # 如果low与high未重合,high指向的元素不比基准元素小,则high向左移动
        while low < high and alist[high] >= mid:
            high -= 1
        # 将high指向的元素放到low的位置上
        alist[low] = alist[high]

        # 如果low与high未重合,low指向的元素比基准元素小,则low向右移动
        while low < high and alist[low] < mid:
            low += 1
        # 将low指向的元素放到high的位置上
        alist[high] = alist[low]

    # 退出循环后,low与high重合,此时所指位置为基准元素的正确位置
    # 将基准元素放到该位置
    alist[low] = mid

    # 对基准元素左边的子序列进行快速排序
    quick_sort(alist, start, low-1)

    # 对基准元素右边的子序列进行快速排序
    quick_sort(alist, low+1, end)


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

time complexity

  • The optimal time complexity: O (nlogn)
  • The worst time complexity: O (n2)
  • Stability: Unstable
Published 146 original articles · won praise 66 · views 50000 +

Guess you like

Origin blog.csdn.net/qq_38923792/article/details/96867862