Using python implement bubble sort algorithm

Bubble sort, a classic sort algorithm, due to run algorithms, the extreme value will be like bubbles underwater gradually coming out of the same, hence the name.

Bubble sort process compares the size of the adjacent elements, according to the size and location of the exchange, so that the left bubbling from the list, the last maximum value will emerge sequentially from the right end.

 

d088a9356bb0dc31844735204ffb458d1c158f78

python implement bubble sort:

def bubble_sort(nums):

    for i in range(len(nums) - 1):

        for j in range(len(nums) - i - 1):

            if nums[j] > nums[j + 1]:

                nums[j], nums[j + 1] = nums[j + 1], nums[j]

    return nums

Python core idea is to achieve a bubble sort the list by the end of an iterative cycle element, then through a loop element so that two adjacent elements after the comparison, thereby sequentially moved to the end of the maximum value, as shown schematically.

9af0e4278f9c9fb8267f4be6f8590b611877a85b

Gif wanted to put a figure, do not put on a bit of a problem.

 

About the time complexity of the bubble sort, the realization of the above code python time complexity of n squared , of course, can then consider the extreme cases: when the queue is sorted in ascending or descending sorted , can only scan from small to large in good order again to end sort case time complexity is O (n), if it is descending, then it is necessary to scan n-1 times, while switching requires a relatively n-1 times the square of the time complexity of n.

Guess you like

Origin www.cnblogs.com/pypypy/p/11960134.html