Introduction:
Bubble sort is a fundamental sorting algorithm that can be implemented using Python. This tutorial provides a comprehensive guide to implementing the bubble sort algorithm. Through practical examples and explanations, you’ll understand the logic behind bubble sort and how it efficiently sorts a list of elements in ascending order.
Code:
def bubble_Sort(list1): # Number of passes
n = len(list1)
for i in range(n):
for j in range(0, n-i-1): # size -i-1 because last i elements are already sorted
if list1[j] > list1[j+1]: # Swap element at jth position with (j+1)th position
list1[j], list1[j+1] = list1[j+1], list1[j]
numList = [8, 7, 13, 1, -9, 4]
bubble_Sort(numList)
print("The sorted list is:")
for i in range(len(numList)):
print(numList[i], end=" ")
Logic:
- Define the bubble_sort function that takes a list list1 as input.
- Get the length of the list n.
- Use nested loops to perform the bubble sort:
- The outer loop runs for n passes (one pass for each element).
- The inner loop compares adjacent elements and swaps them if necessary, effectively moving the largest element to the end of the list.
- The sorted list is printed after the sorting process is complete.
Output:
>The sorted list is:
>>-9 1 4 7 8 13