By: Editorial Staff | Last Updated: | In: Python Tutorial
Hello friends, hope you are doing good. In this tutorial, I am going to share a python program to sort the element using bubble sort algorithm.
Bubble sort is the very simple sorting algorithm and it is a comparison-based algorithm in which each pair of adjacent elements compared and then elements are swapped if they are not in sorted in order. If you a college student or just started learning the Python programming language, then this program will help you more to the better understanding of bubble sort.
Below is the algorithms to sort the number using Bubble sort.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
begin BubbleSort(list) for all elements of the list if list[i] > list[i+1] swap(list[i], list[i+1]) end if end for return list end BubbleSort |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
def bubbleSort(arr): n = len(arr) for i in range(n): swapped = False for j in range(0, n-i-1): if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] swapped = True if swapped == False: break arr = [45, 30, 25, 10, 5, 18, 70] bubbleSort(arr) print ("Sorted array :") for i in range(len(arr)): print ("%d" %arr[i],end=" ") |
Sorted array:
5, 10, 18, 25, 30, 45, 70
Liked this program? Do Like & share with your friends.
Editorial Staff at FreeWebMentor is a team of professional developers leads by Prem Tiwari View all posts by Editorial Staff