Python Program to Find the Second Largest Number in a List using Bubble Sort

Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. Although Bubble Sort is not the most efficient sorting algorithm, it’s easy to understand and implement.

Problem Statement

You are given a list of integers. Your task is to write a Python program to find the second largest number in the list using the Bubble Sort algorithm.

Python Program to Find the Second Largest Number in a List using Bubble Sort

def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]

def second_largest(arr):
    bubble_sort(arr)
    if len(arr) < 2:
        return None
    return arr[-2]

# Example usage
if __name__ == "__main__":
    try:
        input_list = [int(x) for x in input("Enter a list of numbers separated by spaces: ").split()]
        result = second_largest(input_list)
        if result is not None:
            print("The second largest number is:", result)
        else:
            print("List should have at least two numbers.")
    except ValueError:
        print("Invalid input. Please enter a valid list of numbers.")

How it Works

  1. Function Definitions:
    • bubble_sort(arr): This function implements the Bubble Sort algorithm. It iterates through the list arr and compares adjacent elements. If an element is greater than its next element, they are swapped. This process is repeated for each element, causing the largest element to “bubble” to the end of the list.
    • second_largest(arr): This function takes a list arr as input, sorts it using the bubble_sort function, and then returns the second-to-last element, which will be the second largest number in the list. If the list has fewer than two elements, the function returns None.
  2. Example Usage Section:
    • The program begins execution here when you run the script.
    • It asks the user to input a list of numbers separated by spaces.
    • It converts the input string into a list of integers using a list comprehension.
    • It then calls the second_largest function with the input list.
    • If the result is not None, it prints the second largest number. If the list has fewer than two numbers, it prints an appropriate message.
  3. Bubble Sort Algorithm:
    • The bubble_sort function sorts the input list using the Bubble Sort algorithm.
    • The outer loop runs n times, where n is the length of the list.
    • The inner loop compares adjacent elements and swaps them if they are in the wrong order. This loop runs n - i - 1 times, where i is the current iteration of the outer loop.
    • After completing the Bubble Sort, the largest number will be at the last position in the list.
  4. Finding the Second Largest:
    • After sorting the list, the second largest number will be the element at the second-to-last position in the list.
  5. Output:
    • The program outputs the second largest number in the list or appropriate messages if the list is empty or has fewer than two elements.

The program utilizes the Bubble Sort algorithm to sort the list and then extracts the second largest number from the sorted list.

Input/ Output

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...