Algorithm----Bubble Sort Sorting

Bubble Sort is a simple sorting algorithm. It iterates over the sequence to be sorted, comparing two elements at a time, and swapping them if they are in the wrong order. The job of traversing the sequence is to repeat until no more swaps are needed, that is, the sequence has been sorted. The name of this algorithm comes from the fact that the smaller elements are slowly "floated" to the top of the sequence by swapping.

The bubble sort algorithm works as follows:

  • Compare adjacent elements. If the first is larger than the second (in ascending order), swap the two.
  • Do the same for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. After this step, the last element will be the largest number.
  • Repeat the above steps for all elements except the last one.
  • Keep repeating the above steps for fewer and fewer elements each time, until there are no pairs of numbers to compare.

Analysis of bubble sort

Illustration of the exchange process (for the first time):


Then we need to perform n-1 bubbling processes, and the number of comparisons corresponding to each time is shown in the following figure:


The implementation process of bubble sort is similar to the following figure



The implementation code is as follows:

def bubble_sort (a_list):
     """
         Bubble sort
        only
 uses a sequence list to illustrate its main idea, not a linked list, but the idea is the same, but the linked list is slightly more complicated     """
 n = len (a_list)
     for j in range ( 0 , n- 1 ):
         # The outer loop controls how many times to execute
 for i in range ( 0 , nj- 1 ):
             # The inner loop controls where to stop from the beginning, not every time Finally list[n-1], as the number of executions increases, the length of the inner loop will gradually shorten
 if a_list[i] > a_list[i+ 1 ]:
                        
                a_list[i], a_list[i+1] = a_list[i+1], a_list[i]

if __name__ == "__main__":
    lisi1 = [ 5 , 7 , 1 , 45 , 4556 , 0 , 26 ]
     print ( "Before sorting: %s" %lisi1)
    bubble_sort(lisi1)
    print ( "After sorting: %s" %lisi1)

operation result:

Before sorting: [5, 7, 1, 45, 4556, 0, 26]
After sorting: [0, 1, 5, 7, 26, 45, 4556]


Process ended with exit code 0


Guess you like

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