Bubble Sort Algorithm in Python

thumbnail

In this tutorial, you will learn to create bubble sort algorithm to sort some values inside array or list from the smallest to the largest number in python.

The source code is explained in below:

def bubbleSort(arr):
  tempArr = arr
  for num in range(len(tempArr)-1,0,-1):
    for i in range(num):
      if tempArr[i]>tempArr[i+1]:
        temp = tempArr[i]
        tempArr[i] = tempArr[i+1]
        tempArr[i+1] = temp
  return tempArr
        
arr = [4,9,1,3,7,2,5,6,8]
print("arr:")
print(arr)
sortedArr = bubbleSort(arr)
print("Sorted array using bubbleSort(): ")
print(sortedArr)

The output will be:

arr:
[4, 9, 1, 3, 7, 2, 5, 6, 8]
Sorted array using bubbleSort(): 
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Back To Top