Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Find the Second Largest Number in a List Using Bubble Sort
Finding the second largest number in a list can be accomplished using bubble sort to first arrange elements in ascending order, then accessing the second-to-last element. Bubble sort repeatedly compares adjacent elements and swaps them if they are in the wrong order.
Understanding Bubble Sort
Bubble sort works by comparing each pair of adjacent elements and swapping them if the first element is greater than the second. This process continues until no more swaps are needed.
Complete Implementation
Here's a complete program that demonstrates finding the second largest number using bubble sort ?
def bubble_sort(numbers):
"""Sort the list using bubble sort algorithm"""
n = len(numbers)
for i in range(n):
for j in range(0, n - i - 1):
if numbers[j] > numbers[j + 1]:
# Swap elements
numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]
return numbers
def get_second_largest(numbers):
"""Find second largest number after sorting"""
if len(numbers) < 2:
return None
sorted_numbers = bubble_sort(numbers.copy())
return sorted_numbers[-2] # Second from last
# Example with predefined list
my_list = [64, 34, 25, 12, 22, 11, 90]
print("Original list:", my_list)
second_largest = get_second_largest(my_list)
print("Second largest number:", second_largest)
# Show the sorted list
sorted_list = bubble_sort(my_list.copy())
print("Sorted list:", sorted_list)
Original list: [64, 34, 25, 12, 22, 11, 90] Second largest number: 64 Sorted list: [11, 12, 22, 25, 34, 64, 90]
Step-by-Step Example
Let's trace through the bubble sort process with a smaller example ?
def bubble_sort_with_steps(numbers):
"""Bubble sort with step-by-step output"""
n = len(numbers)
print(f"Initial list: {numbers}")
for i in range(n):
swapped = False
for j in range(0, n - i - 1):
if numbers[j] > numbers[j + 1]:
# Swap elements
numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]
swapped = True
print(f"After pass {i + 1}: {numbers}")
if not swapped:
print("No swaps made, list is sorted!")
break
return numbers
# Example
test_list = [5, 2, 8, 1, 9]
sorted_list = bubble_sort_with_steps(test_list)
print(f"\nSecond largest: {sorted_list[-2]}")
Initial list: [5, 2, 8, 1, 9] After pass 1: [2, 5, 1, 8, 9] After pass 2: [2, 1, 5, 8, 9] After pass 3: [1, 2, 5, 8, 9] After pass 4: [1, 2, 5, 8, 9] No swaps made, list is sorted! Second largest: 8
Handling Edge Cases
It's important to handle cases where the list might not have enough elements ?
def find_second_largest_safe(numbers):
"""Safely find second largest with error handling"""
if len(numbers) < 2:
return "List must have at least 2 elements"
# Remove duplicates and sort
unique_numbers = list(set(numbers))
if len(unique_numbers) < 2:
return "List must have at least 2 unique elements"
# Sort using bubble sort
n = len(unique_numbers)
for i in range(n):
for j in range(0, n - i - 1):
if unique_numbers[j] > unique_numbers[j + 1]:
unique_numbers[j], unique_numbers[j + 1] = unique_numbers[j + 1], unique_numbers[j]
return unique_numbers[-2]
# Test cases
test_cases = [
[1, 2, 3, 4, 5],
[5, 5, 5, 5],
[10],
[],
[7, 2, 7, 2, 9]
]
for i, case in enumerate(test_cases, 1):
result = find_second_largest_safe(case)
print(f"Test {i}: {case} ? Second largest: {result}")
Test 1: [1, 2, 3, 4, 5] ? Second largest: 4 Test 2: [5, 5, 5, 5] ? Second largest: List must have at least 2 unique elements Test 3: [10] ? Second largest: List must have at least 2 elements Test 4: [] ? Second largest: List must have at least 2 elements Test 5: [7, 2, 7, 2, 9] ? Second largest: 7
Comparison with Other Methods
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Bubble Sort | O(n²) | O(1) | Learning, small datasets |
| Built-in sort() | O(n log n) | O(1) | Production code |
| Two-pass scan | O(n) | O(1) | Optimal performance |
Conclusion
Using bubble sort to find the second largest number provides a clear understanding of sorting algorithms, though it's not the most efficient approach. For educational purposes, it demonstrates both sorting and list manipulation concepts effectively.
