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.