Classical sorting algorithm - bubble sorting and its optimization (python code implementation)

Bubble Sort

        Bubble sorting is a very classic sorting algorithm among sorting algorithms. It has a relatively simple idea and is easy to understand and implement. It is generally the first sorting algorithm that beginners come into contact with.

        The reason why it is called bubble sorting is because during the sorting process, like soda bubbling, elements will gradually rise to the top (last) step by step.

basic idea

        By comparing one by one, each pass determines the largest or smallest element among the remaining elements to be sorted until all elements are in order. Specifically, in each sorting, the elements are compared in pairs. Starting from the starting position, the current element is compared with the next element. If the two elements are in order, ignore and move one element backward to continue the backward comparison. , if it does not match, exchange the elements first, then move one element backward and continue to compare backwards until the end of this trip.

Features

average time complexity best case worst case space complexity sort by stability
O(n^{2}) O(n) O(n^{2}) O(1) In-place Stablize

Detailed steps

Columns to be sorted:

1 42 65 876 34 656 4

ascending order 

Sort the first pass:

1 42 65 876 34 656 4
1 42 65 876 34 656 4
1 42 65 876 34 656 4
1 42 65 34 876 656 4
1 42 65 34 656 876 4
1 42 65 34 656 4 876

Second sorting:

1 42 65 34 656 4 876
1 42 65 34 656 4 876
1 42 34 65 656 4 876
1 42 34 65 656 4 876
1 42 34 65 4 656 876

The third sort:

1 42 34 65 4 656 876
1 34 42 65 4 656 876
1 34 42 65 4 656 876
1 34 42 4 65 656 876

The fourth sort:

1 34 42 4 65 656 876
1 34 42 4 65 656 876
1 34 4 42 65 656 876

Fifth sorting:

1 34 4 42 65 656 876
1 4 34 42 65 656 876

The sixth sorting:

     

1 4 34 42 65 656 876

 Ordinal sequence:

1 4 34 42 65 656 876

optimization

        In fact, the bubble sort algorithm can be further optimized to make it more efficient. Let's take a more extreme example below.

        Now there is a sequence to be sorted, which is already an ordered sequence, as follows:

Then our bubble sorting algorithm will perform the following sorting operations at this time:

        We can clearly see that when our sequence to be sorted is already in order, the bubble sorting algorithm will still perform certain useless operations, which reduces the efficiency of the algorithm, so the basic bubble sorting can be performed Certain improvements:

        We set a flag to record that if we perform a sorting operation without any element exchange, it means that the column to be sorted is already in order, so we can end the sorting operation in advance.

advanced optimization

        Through the above algorithm optimization, the efficiency of bubble sorting has been improved to a certain extent. In fact, we can further optimize the bubble sorting algorithm. We can use two-way bubbling in each sorting process (while finding the maximum and minimum values ), which further improves the efficiency of algorithm sorting to a certain extent.

column to be sorted 1 42 65 876 34 656 4
first trip 1 4 42 65 34 656 876
second trip 1 4 34 42 65 656 876
third trip 1 4 34 42 65 656 876

python code

# 冒泡排序
def bubbleSort(arr):
    for i in range(1, len(arr)):
        for j in range(0, len(arr)-i): # 每排序一趟就少一个元素需要进行比较(后面的元素已经有序)
            #if arr[j] > arr[j + 1]:  # 升序
            if arr[j] < arr[j + 1]:   # 降序
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr


if __name__=="__main__":
    nums = [1, 42, 65, 876, 34, 656, 4, 6757, 89, 24, 65, 42]
    print("start:", nums)
    print("冒泡 :", bubbleSort(nums))

optimize python code

# 冒泡排序
def bubbleSort(arr):
    for i in range(1, len(arr)):
        flag = False  # 设置标志位,判断当前趟次是否有元素交换
        for j in range(0, len(arr)-i): # 每排序一趟就少一个元素需要进行比较(后面的元素已经有序)
            #if arr[j] > arr[j + 1]:  # 升序
            if arr[j] < arr[j + 1]:   # 降序
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                flag = True  # 记录发生了交换
        if flag==False: # 如果元素未发生交换,说明待排序列已经是有序序列,则提前结束排序
            break
    return arr


if __name__=="__main__":
    nums = [1, 42, 65, 876, 34, 656, 4, 6757, 89, 24, 65, 42]
    print("start:", nums)
    print("冒泡 :", bubbleSort(nums))

Further optimize the python code

# 冒泡排序
def bubbleSort(arr):
    for i in range(1, len(arr)):
        l = 0  # 记录左边元素下标
        r = len(nums) - 1  # 记录右边元素下标
        flag = False  # 设置标志位,判断当前趟次是否有元素交换
        # 正向排序最大值
        for j in range(l, r):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                flag = True

        if not flag:
            break
        # 反向排序最小值
        for j in range(r, l, -1):
            if arr[j] < arr[j - 1]:
                arr[j], arr[j - 1] = arr[j - 1], arr[j]

        print(nums)
    return arr


if __name__=="__main__":
    nums = [1, 42, 65, 876, 34, 656, 4, 6757, 89, 24, 65, 42]
    print("start:", nums)
    print("冒泡 :", bubbleSort(nums))

Guess you like

Origin blog.csdn.net/qq_41750911/article/details/125077898