SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Y Daniel Lang
Chapter:
0.lists
Exercise:
Programming Excercises
Question:16 | ISBN:978013274719 | Edition: 6

Question

(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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.