Get Second Largest Number in Python List Using Bubble Sort
Last Updated :
07 Feb, 2024
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.
- Bubble Sort Algorithm:
- 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.
- 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.
Python3
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 find_second_largest(arr):
bubble_sort(arr)
return arr[ - 2 ]
numbers = [ 12 , 34 , 7 , 23 , 32 ]
second_largest = find_second_largest(numbers)
print (f "The second largest number is: {second_largest}" )
|
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.
Share your thoughts in the comments
Please Login to comment...