Bubble Sort in Python
Here you will learn the program code of Bubble Sort in Python programming.
What is bubble sort in python
Bubble Sort is an algorithm that sorts an array by repeatedly looping through the array and swapping adjacent elements if they are out of order. The name comes from the fact that elements with higher values bubble up to the top of the array.
Program for bubble sort in python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #Python Bubble Sort program # Bubble Sort Function def bubble_sort(arr): # Setting up swap flag swapped = True while swapped: swapped = False for i in range(len(arr)-1): if arr[i] > arr[i+1]: # Swap elements arr[i], arr[i+1] = arr[i+1], arr[i] # Set flag to True so loop continues swapped = True return arr # Input list arr = [] print("Enter 5 numbers ") for i in range(5): item = input('Input item : ') arr.append(item) # Sorted list sorted_list = bubble_sort(arr) # Print sorted list print(sorted_list) |
Output
Enter 5 numbers
Input item : 2
Input item : 4
Input item : 3
Input item : 1
Input item : 9
[‘1’, ‘2’, ‘3’, ‘4’, ‘9’]
Check out our other Python Programming Examples