Bubble sort

Bubble sort is a very simple sorting algorithm. It is not commonly used because it is inefficient and slower than many other sorting algorithms.
However, it is a great sorting algorithm to learn for beginners. 

It is a stable, in-place, comparison-based sorting algorithm.

To see how this algorithm works in details please watch the video on my youtube channel.   



Time complexity

Worst Case:         О(n2)
Average Case:    О(n2)
Best Case:             О(n2)


📢RecommendedPlease watch the video first of all. Try to understand the algorithm and the idea behind it and then try to implement the algorithm on your own first, before looking at the code down below.


______________________________________________________


🎁code:


def bubble_sort(unsorted_arr):
    for i in range(len(unsorted_arr) - 1): #number of iterations = length - 1
        for j in range(len(unsorted_arr)-1-i): #number of required comparisons per iterations
            if unsorted_arr[j] > unsorted_arr[j + 1]: # if the next element smaller than the current element (next element = the element after the current element) 
                unsorted_arr[j], unsorted_arr[j+1= unsorted_arr[j + 1], unsorted_arr[j] # swap 

    return unsorted_arr


unsorted_arr = [10010442161]
print("Before sorting: ")
print(unsorted_arr)
bubble_sort(unsorted_arr)
print("After sorting:")
print(unsorted_arr)


______________________________________________________

output:

Before sorting:
[100, 10, 44, 2, 16, 1]

After sorting:
[1, 2, 10, 16, 44, 100]

______________________________________________________



Comments