Bubble Sort
A sorting algorithm where by adjacent elements are repeatedly compared. They will be swapped if they happen to be in the wrong order.
Best Time Complexity: O(n2)
Worse Time Complexity: O(n2)
Usage
bubble_sort(lst:list, key:Callable = lambda x:x, visualise:bool = False, animate:bool = False)
Parameters:
lst : List
A list of elements to be sorted
key : Callable
A custom function on how the elements should be sorted
visualise : Boolean
If true, the generator object will record the state of the list after each iteration
animate : Boolean
If true, the generator object will record each change in the state of the list
Returns:
Generator
A generator object is analogous to a lazy iterator
Comments
- This function does not print or perform animations. Find out how to do that here.
- As this function returns a generator, perform list comprehension to reveal sorted result.
Example
from jellybeans.algos import bubble_sortlst = [9, 19, 1, 17, 6, 20, 4, 13, 15, 3][i for i in bubble_sort(lst)]print(lst) # [1, 3, 4, 6, 9, 13, 15, 17, 19, 20]