Bubble Search
Bubble search is one of the most common and basic sorting technique which is used to sort an array. Most common parameters are array which is to be sorted and a size of an array (optional).
Technique used in Bubble Sort
In bubble sort, sorting happens based on comparison between two element, like which one is greater or lesser.
Eg:
list = [2, 1]
if list[0] > list[1]:
list[0], list[1] = list[1], list[0]
- Above the list become [1, 2]. Here we compare 0th and 1th index, if the 0th index value is greater than 1th index value then the swapping will happen.
- This process will be applied to all the elements in an array until the array is sorted.
- We need to apply this process iteratively to sort an array of N size.
Implementation of Bubble Sort!
def bubble_sort (array: list) -> list:
for i in range(0, len(array) - 1):
for j in range(0, len(array) - 1 - i):
if array[j] > array[j + 1]:
array[j], array[j+1] = array[j+1], array[j]
return arr
- The outer loop will be run for N time to move all the at it correct position. The outer loop act as pass which is mentioned in the above image.
- The inner loop will make comparison between current and next elements, if the condition meet then the swap will happen.
Time complexity is O(N^2)
print(Happy Coding)
Top comments (0)