VOOZH about

URL: https://www.geeksforgeeks.org/python/get-second-largest-number-in-python-list-using-bubble-sort/

⇱ Get Second Largest Number in Python List Using Bubble Sort - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Get Second Largest Number in Python List Using Bubble Sort

Last Updated : 23 Jul, 2025

Finding the second-largest number in a list is a common programming task that involves sorting the list in ascending order. Bubble sort is a simple sorting algorithm that can be used for this purpose. In this article, we will explore the logic behind finding the second largest number using bubble sort and provide a Python program to implement it.

Main Logic

  • The bubble sort algorithm works by repeatedly swapping adjacent elements if they are in the wrong order.
  • In each pass, the largest unsorted element "bubbles up" to its correct position at the end of the list.
  • After the first pass, the largest element is in the last position.
  • After the second pass, the second-largest element is in the second-to-last position, and so on.
  1. Bubble Sort Algorithm:
  2. Identifying the Second Largest:
    • To find the second-largest number, we perform the bubble sort and keep track of the largest and second-largest elements during each pass.
  3. Mathematical Representation:
    • Let n be the length of the list.
    • After the first pass, the largest element is at index n-1.
    • After the second pass, the second-largest element is at index n-2.

Find The Second Largest Number In A List Using Bubble Sort

Example :

  • The bubble_sort function implements the Bubble Sort algorithm to sort a given list in ascending order.
  • The outer loop runs n times (where n is the length of the list), and the inner loop iterates through the unsorted portion of the list, swapping adjacent elements if they are in the wrong order.
  • The find_second_largest function uses the bubble_sort function to sort the list and then returns the second-to-last element, which is the second-largest number.
  • The example usage demonstrates finding the second largest number in the list [12, 34, 7, 23, 32] and prints the result using the print statement.

Output
The second largest number is: 32

Conclusion

In this conclusion ,as we discussed the logic behind finding the second largest number in a list using the bubble sort algorithm. The key idea is to perform a bubble sort and keep track of the largest and second-largest elements during each pass. The provided Python program demonstrates the implementation of this logic, showcasing how bubble sort can be used to efficiently find the second-largest number in a list.

Comment
Article Tags: