เรียงลำดับ List ด้วย Bubble Sort แล้วเลือกตัวที่สองจากท้าย (index -2)
ตัวอย่างโค้ด
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
คำอธิบาย
- รับจำนวนสมาชิกและค่าสมาชิกจากผู้ใช้
- เรียงลำดับ List ด้วย Bubble Sort (น้อยไปมาก)
- เลือกสมาชิก index
n-2(ตัวที่สองจากท้าย)