Bubble Sort Optimised
An extention to the normal bubble sort. The function stops when there are no swaps made in 1 iteration
Best Time Complexity: O(n)
Worse Time Complexity: O(n2)
Usage
bubble_sort_optimised(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_sort_optimisedlst = [9, 19, 1, 17, 6, 20, 4, 13, 15, 3][i for i in bubble_sort_optimised(lst)]print(lst) # [1, 3, 4, 6, 9, 13, 15, 17, 19, 20]