Bubble Sort is a sorting algorithm that arranges the elements of an array in ascending order (from lowest to highest).
Conceptually, the algorithm works by repeatedly comparing adjacent elements in the array. If the current element is greater than the next one, the two elements are swapped. The process starts by comparing the first and second elements, then the second and third, and continues through the array. Each pass places the largest unsorted element in its correct position. This process is repeated until the entire array is sorted.
To implement the Bubble Sort algorithm in a programming language, the following components are required:
-
An array containing the values to be sorted.
-
An inner loop that iterates through the array, comparing adjacent elements and swapping them if the first element is greater than the next. With each pass, this loop runs one fewer iteration because the largest elements are already in their correct positions.
-
An outer loop that determines how many times the inner loop executes. For an array of n elements, the outer loop runs n − 1 times.
Python Code
# List of numbers that will be sorted using Bubble Sort
numbers = [64, 34, 35, 2, 22, 11, 90, 5]
# Store the total number of elements in the list
length = len(numbers)
# Outer loop controls the number of passes through the list
# After each pass, the largest unsorted value moves to its correct position
for pass_index in range(length - 1):
# Inner loop compares adjacent elements
# The range decreases after each pass because the last elements are already sorted
for current_index in range(length - pass_index - 1):
# Compare the current element with the next element
if numbers[current_index] > numbers[current_index + 1]:
# Swap the elements if they are in the wrong order
numbers[current_index], numbers[current_index + 1] = (
numbers[current_index + 1],
numbers[current_index]
)
# Output the sorted list
print("Sorted array:", numbers)
Output
Sorted array: [2, 5, 11, 22, 34, 35, 64, 90]