Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chương trình Python tìm số lớn thứ hai trong List dùng Bubble Sort

Khi cần tìm số lớn thứ hai trong list dùng bubble sort, định nghĩa 'bubble_sort' sắp xếp list. Sau đó 'get_second_largest' trả về phần tử thứ hai từ cuối.

Minh họa:

Ví dụ

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])

Kết quả

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

Giải thích

  • Định nghĩa list rỗng.
  • Nhập số phần tử từ user.
  • Nhập các phần tử từ user.
  • Lặp list, append phần tử.
  • Sắp xếp list bằng bubble sort.
  • Hiển thị phần tử thứ hai từ cuối output.