Python 程式使用氣泡排序查詢列表中第二大數字
如果需要使用氣泡排序查詢列表中第二大數字,則定義名為“bubble_sort”的方法,該方法對列表中的元素進行排序。完成後,定義名為“get_second_largest”的另一個方法,該方法將列表中倒數第二個元素返回作為輸出。
以下是對此方法的演示 -
示例
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])輸出
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
說明
定義一個空列表。
使用者指定元素數。
使用者輸入元素。
遍歷列表,並將元素新增到列表中。
使用氣泡排序對列表中的元素進行排序。
倒數第二個元素顯示在控制檯輸出中。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP