
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Second Largest Number in a List Using Bubble Sort
When it is required to find the second largest number in a list using bubble sort, a method named ‘bubble_sort’ is defined, that sorts the elements of the list. Once this is done, another method named ‘get_second_largest’ is defined that returns the second element from the end as output.
Below is the demonstration of the same −
Example
my_list = [] my_input = int(input("Enter the number of elements...")) for i in range(1,my_input+1): b=int(input("Enter the element...")) my_list.append(b) for i in range(0,len(my_list)): for j in range(0,len(my_list)-i-1): if(my_list[j]>my_list[j+1]): temp=my_list[j] my_list[j]=my_list[j+1] my_list[j+1]=temp print('The second largest element is:') print(my_list[my_input-2])
Output
Enter the number of elements...5 Enter the element...1 Enter the element...4 Enter the element...9 Enter the element...11 Enter the element...0 The second largest element is: 9
Explanation
An empty list is defined.
The number of elements is taken by user.
The elements are entered by the user.
The list is iterated over, and the elements are appended to the list.
The elements of the list are sorted using bubble sort.
The second element from the last is displayed as output on the console.
Advertisements