Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order.
Python Program for Bubble Sort
The provided Python code implements the Bubble Sort algorithm, which sorts an array by repeatedly comparing adjacent elements and swapping them if they are in the wrong order. The algorithm iterates through the array multiple times, with each pass pushing the largest unsorted element to its correct position at the end. The code includes an optimization: if no swaps are made during a pass, the array is already sorted, and the sorting process stops. The example initializes an array, applies the bubbleSort function to sort it, and prints the sorted array. After sorting, the output is: [11, 12, 22, 25, 34, 64, 90], indicating ascending order.
Python3
def bubbleSort(arr):
n = len (arr)
swapped = False
for i in range (n - 1 ):
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
arr = [ 64 , 34 , 25 , 12 , 22 , 11 , 90 ]
bubbleSort(arr)
print ( "Sorted array is:" )
for i in range ( len (arr)):
print ( "% d" % arr[i], end = " " )
|
OutputSorted array is:
11 12 22 25 34 64 90
Time Complexity: O(n2).
Auxiliary Space: O(1).
Please refer complete article on Bubble Sort for more details!
Python3
def bubblesort(elements):
swapped = False
for n in range ( len (elements) - 1 , 0 , - 1 ):
for i in range (n):
if elements[i] > elements[i + 1 ]:
swapped = True
elements[i], elements[i + 1 ] = elements[i + 1 ], elements[i]
if not swapped:
return
elements = [ 39 , 12 , 18 , 85 , 72 , 10 , 2 , 18 ]
print ( "Unsorted list is," )
print (elements)
bubblesort(elements)
print ( "Sorted Array is, " )
print (elements)
|
OutputUnsorted list is,
[39, 12, 18, 85, 72, 10, 2, 18]
Sorted Array is,
[2, 10, 12, 18, 18, 39, 72, 85]
Time Complexity: O(n2). However in practice, this optimized version might take less time as when array gets sorted, function would return.
Auxiliary Space: O(1).