Python: program to find the largest number in a list using bubble sort #python #program #code

preview_player
Показать описание
Python program to find the second largest number in a list using bubble sort

#python #programmer #pythondeveloper #interviewquestion #pythonprogramming #pythontutorial #code
Рекомендации по теме
Комментарии
Автор

bubble sort has a complexity of n^2, you dont need a sorting algorithm just to find a max value in a list

thecodebear
Автор

A simpler and more efficient solution can be done without requiring a sorting algorithm. This can be done in O(n) time.

At a high level, pass trough the list once to find the largest. Then, pass through the list again and find the number that is greatest but still less than the largest. This will be your second largest.
This solution is more intuitive and easy to follow, and does not require any swapping or copying. In addition, the linear time complexity is nice.

a = []
n = int(input("Enter num elements: "))
for i in range(1, n+1):
b = int(input("Element: "))
a.append(b)

# Done in O(n) time...

largest = 0
second_largest = 0

for i in range(0, len(a)):
if(a[i] >= largest):
largest = a[i]

for i in range(0, len(a)):
if(a[i] >= second_largest and a[i] < largest):
second_largest = a[i]

print("Largest: ", largest)
print("Second largest: ", second_largest)

lucass
join shbcf.ru