Sorting algorithm-bubble sorting and optimization

Bubble Sorting

Basic idea : compare the values ​​of adjacent elements by treating the sorted sequence from front to back (starting from the element with the smaller subscript), and exchange if the reverse order is found, so that the element with the larger value gradually moves from the front to the back. It gradually rises
upward like air bubbles under the water .

Because in the process of sorting, each element is constantly approaching its position. If there is no exchange in a comparison, it means that the sequence is ordered. Therefore, a flag should be set in the sorting process to determine whether the element has been exchanged. Thereby reducing unnecessary comparisons. (The optimization mentioned here can be carried out after the bubble sort is written)

Put a picture, please understand
by yourself. Here is the specific process of bubbling:
Insert picture description here

Analysis of algorithm ideas

Here is an example to explain, there is an unordered array arr [3,9, -1,0, -2]

The first comparison: we start with the first number and see if the first number is larger than the second number: if it is greater, then swap the positions of the two, otherwise no operation is performed. Repeat this operation until the penultimate position, which is arr.length-1. Through this comparison we found the largest number 9 in this array, which will bubble up to the end of the array.

arr[ 3,-1,0,-2,9 ]

Second comparison: This comparison is almost the same as the first. The only change is that you do n’t need to compare the penultimate and penultimate.

arr[ -1,0,-2,3,9]

The third comparison: here is the same as above, but the comparison is one less time.

arr[-1,-2,0,3,9]

Fourth comparison: no explanation, sum up by yourself.

arr[-2,-1,0,3,9]

At this point, the sorting operation of the array is over. You can see that each comparison is to move the maximum value of the current comparison part to the end of the current sorting part of the array by swapping. Each loop is equivalent to adding an already sorted number.

arr = [0 for i in range(8000)]
for i in range(8000):
    arr[i]=random.randint(0,8000)
#基本的冒泡排序
def BubleSort(arr):
    temp = 0
    #总共要进行数组长度减1的大循环
    for i in range(len(arr)-1):
    #每次内循环都会冒出一个最小或者最大值,故下次循环比较次数-1
        for j in range(len(arr)-1-i):
            if arr[j]>arr[j+1]:
                t=arr[j]
                arr[j]=arr[j+1]
                arr[j+1]=t

print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
BubleSort(arr)
print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
#输出结果
print("普通版的冒泡排序")
print(arr)

If you have understood before, please take a look at the above code, if conditions permit. You can run it on your computer. You will find that when the data reaches 8000, the time efficiency of the computer to use bubble sort is not high. In theory, the time complexity of bubble sort is O (n ^ 2). It takes about 13 seconds to get results on my computer. This time is related to hardware conditions. If your computer is in better condition, the time will be shorter. But how to improve the algorithm?

Bubble sort optimization

In fact, you will find that if the data was originally ordered in time, or partially ordered, such as 1, 2, 3, 4, 5. In fact, when I traverse, I can find that it has not entered the exchange statement once. Ordered array. After a slight modification, the code is as follows:

arr2 = [0 for i in range(8000)]
for i in range(8000):
    arr2[i]=random.randint(0,8000)
#冒泡排序优化
def BubleSort2(arr):
    temp = 0
    flag = False
    #总共要进行数组长度减1的大循环
    for i in range(len(arr)-1):
        flag = False
    #每次内循环都会冒出一个最小或者最大值,故下次循环比较次数-1
        for j in range(len(arr)-1-i):
            if arr[j]>arr[j+1]:
                flag = True
                t=arr[j]
                arr[j]=arr[j+1]
                arr[j+1]=t
        #如果没有一次进入交换语句,说明后面的数字都已经有序
        if flag == False:
            break
print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
BubleSort2(arr2)
print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
print("优化后的冒泡排序")
print(arr2)

You can test whether the running time is shortened on your computer, but when I test it on my computer, the difference is not big. Occasionally shortens the run time by one second, sometimes even makes no difference.

Published 27 original articles · praised 2 · visits 680

Guess you like

Origin blog.csdn.net/qq_44273739/article/details/105182441