(Bubble sort) Write a sort function that uses the bubble-sort algorithm. The bubble-sort algorithm makes several passes through the list. On each pass, successive neighboring pairs are compared. If a pair is in decreasing order, its values are swapped; otherwise, the values remain unchanged. The technique is called a bubble sort or sinking sort because the smaller values gradually “bubble” their way to the top and the larger values “sink” to the bottom. Write a test program that reads in ten numbers, invokes the function, and displays the sorted numbers.
Bubble Sor Program Code:
# Bubble sort function
def bubbleSort(numbers):
n = len(numbers)
# Traverse through all elements in the list
for i in range(n - 1):
# Last i elements are already in place
for j in range(0, n - i - 1):
# Compare adjacent elements
if numbers[j] > numbers[j + 1]:
# Swap the elements if they are in decreasing order
numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]
# Test program
def main():
# Prompt the user to enter ten numbers
numbers = []
print("Please enter TEN numbers below: ")
for _ in range(10):
inputNum = int(input("Enter a number: "))
numbers.append(inputNum)
# Sort the numbers using bubble sort
bubbleSort(numbers)
# Display the sorted numbers
print("\nSorted numbers:")
for inputNum in numbers:
print(inputNum)
# Call the test program
main()
Executed Output:
Please enter TEN numbers below:
Enter a number: 5
Enter a number: 50
Enter a number: 10
Enter a number: 40
Enter a number: 15
Enter a number: 30
Enter a number: 20
Enter a number: 18
Enter a number: 25
Enter a number: 14
Sorted numbers:
5
10
14
15
18
20
25
30
40
50