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

說明

  • 定義一個空列表。

  • 使用者指定元素數。

  • 使用者輸入元素。

  • 遍歷列表,並將元素新增到列表中。

  • 使用氣泡排序對列表中的元素進行排序。

  • 倒數第二個元素顯示在控制檯輸出中。

更新於:19-Apr-2021

776 次瀏覽

開啟您的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.