In this lesson on python coding, we will talk about one of the fundamental algorithms in computer science for sorting Bubble Sort. Bubble sort algorithm is a very common question for python coding interviews. This article will help if you are preparing for a python coding interview, so let's try to write a simple python program to implement the bubble sort in python.
def bubble_sort(num_list): for items in range(len(num_list)-1,0,-1): for item in range(items): if num_list[item] > num_list[item+1]: # Swap temp = num_list[item] num_list[item] = num_list[item+1] num_list[item+1] = temp return num_list print bubble_sort([54,26,93,17,77,31,44,55,20])
# Python program for implementation of Bubble Sort def bubbleSort(arr): n = len(arr) # Traverse through all array elements for i in range(n): # Last i elements are already in place for j in range(0, n-i-1): # traverse the array from 0 to n-i-1 # Swap if the element found is greater # than the next element if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] # Driver code to test above arr = [64, 34, 25, 12, 22, 11, 90] bubbleSort(arr) print ("Sorted array is:") for i in range(len(arr)): print ("%d" %arr[i]),
Both programs will print sort array as output.
Thank you for reading.
Hello, I am Harendra Kumar Kanojiya - Owner of this website and a Fullstack web developer. I have expertise in full-stack web development using Angular, PHP, Node JS, Python, Laravel, Codeigniter and, Other web technologies. I also love to write blogs on the latest web technology to keep me and others updated. Thank you for reading the articles.