Python bubble sort

Bubble Sort is a simple sorting algorithm. It iterates over the sequence to be sorted, comparing two elements at a time, and if they are in the wrong order, reverses them.

The job of traversing the sequence is to repeat until there are no more elements to exchange, 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 greater than the second (in ascending order), swap the two as well.

  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.

 Continue to repeat the above steps for the remaining elements until there are no pairs of numbers to compare.

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

 

 


def
bubble_sort(alist): n = len(alist) for j in range(n-1): for i in range(0,n-1): if alist[i] > alist[i+1]: alist[i], alist[i+1] = alist[i+1], alist[i] if __name__ == "__main__": li = [54, 25, 17, 44, 88, 13, 55, 20, 33 ] print li bubble_sort(li) print li

 

time complexity  

  Optimal time complexity: O(n) (indicates that there are no elements that can be exchanged after traversing once, and the sorting ends.)

  Worst time complexity: O(n*n)

  Stability: stable

 

Guess you like

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