Bubble sort is a simple sorting algorithm that repetadely steps through itens lists to be sorted,compares each pair of adjacent items and swaps them if they are in the wrong order.
The pass through the list is repeated until no swaps are needed,which indicates that the list is sorted.The algorithm,which is a comparison sort,is named for the way smaller elements “bubble” to the top of the list.
Although the algorithms is simple,it is too slow and impractical for the most problems even when compared to insertion sort.The first tima the algorithm runs through the array,every value is compared to the next,and swaps the values if the left value is larger than right.This means that the highest value bubbles up,and the unsorted part of the array becomes shorter and shorter until the sorting is done.
def bubbleSort(arr): n = len(arr) for i in range (n-1): swapped = False for j in range (0, n-i-1): if arr[j] > arr [j + 1]: swapped = True arr[j], arr[j + 1] = arr[j + 1], arr[j] if not swapped: return array = [98,45,78,24,56,69,64,12,4,20] bubbleSort(arr) print("Unsorted list is,") print(elements) bubbleSort(arr) print("Sorted Array is,") print(elements)
output:
Unordered list
[98,45,78,24,56,69,64,12,4,20]
Ordered list
[4,12,20,24,45,56,64,69,78,98]