Hướng dẫn bubble sort in python with user input - sắp xếp bong bóng trong python với đầu vào của người dùng

Tôi mới bắt đầu học Python và tôi đã quyết định thử và thực hiện một loại bong bóng.Tôi đã sử dụng mã bên dưới hoạt động OK nếu các số được sắp xếp là 0 đến 9. Sau đó, nó không sắp xếp chúng một cách chính xác.Tôi nghĩ, trong kiến thức hạn chế của tôi rằng điều này là vì nó là một 'danh sách'.

Tôi muốn người dùng có thể nhập các số nhưng để chương trình sắp xếp chúng bất kể độ dài của số.Bất kỳ trợ giúp sẽ được đánh giá cao.

def bubble_sort(items):
    changes=0

    for i in range(len(items)):
        for j in range(len(items)-1-i):#-i = optimised??
            if items[j] > items[j+1]:
                items[j], items[j+1] = items[j+1], items[j]  # Swap
                changes=changes+1

    print(items)
    print("Number of passes =",i)
    print("Number of swaps =",changes)

print("Welcome to a Bubble Sort Algorithm in Python!")

while True:

    print("Enter as many numbers as you want.\n You can choose between 0 and 9.\nLeave a space between each one")
    numbers=input()
    items=numbers.split()

Hỏi ngày 15 tháng 12 năm 2014 lúc 20:24Dec 15, 2014 at 20:24

Hướng dẫn bubble sort in python with user input - sắp xếp bong bóng trong python với đầu vào của người dùng

Thử cái này:

print('welcome to the automatic bubble sorter')
inputted_list = input('please enter a list of numbers seperated by commas: ')
list = inputted_list.split(',')
number_of_items = int(len(list))

sorting_method = input('if you would like your list to be sorted in ascending order, press 1, if you would like it to be sorted in descending order, press 2')
print(list)

if sorting_method == '1':
    position = 0
    Pass = 0
    counter = 1
    while counter == 1:
        number_of_swaps = 1
        counter2 = 0
        permanent_numbers = []
        while number_of_swaps > 0:
            counter2 = counter2 + 1
            number_of_swaps = 0
            while position < number_of_items - 1:
                if int(list[position]) > int(list[position + 1]):
                    number_of_swaps = number_of_swaps + 1
                    item1 = int(list[position])
                    item2 = int(list[position + 1])
                    list[position] = item2
                    list[position + 1] = item1
                position = position + 1
            Pass =  Pass + 1
            print('pass',Pass,':',list)
            position = 0
            if Pass == number_of_items - 1:
                number_of_swaps = 0
            permanent_numbers.append(list[number_of_items - counter2])
        if number_of_swaps == 0:
            counter = 0


    print('total number of passes:', Pass)

    elif sorting_method == '2':
    position = 0
    Pass = 0
    counter = 1
    while counter == 1:
        number_of_swaps = 1
        while number_of_swaps > 0:
            number_of_swaps = 0
            while position < number_of_items - 1:
                if int(list[position]) > int(list[position + 1]):
                    number_of_swaps = number_of_swaps + 1
                    item1 = int(list[position])
                    item2 = int(list[position + 1])
                    list[position] = item2
                    list[position + 1] = item1
                position = position + 1
            Pass =  Pass + 1
            print('pass',Pass,':',list)
            position = 0
            if Pass == number_of_items - 1:
                number_of_swaps = 0

        if number_of_swaps == 0:
            counter = 0


    print('total number of passes:', Pass)  

Đã trả lời ngày 14 tháng 10 năm 2016 lúc 18:20Oct 14, 2016 at 18:20

Hướng dẫn bubble sort in python with user input - sắp xếp bong bóng trong python với đầu vào của người dùng

0

Thử bản đồ:

Tôi đã đề xuất sử dụng bản đồ trước đây, nhưng tôi chỉ nhớ rằng bản đồ trong Python 3.x* mang lại một trình tạo chứ không phải là một danh sách, vì vậy đó là lý do tại sao bạn không thể có độ dài của nó.Câu trả lời cập nhật bên dưới

numbers = input("Enter as many numbers as you want.\n You can choose between 0 and 9.\nLeave a space between each one")
items = [int(num) for num in numbers.split()]

Mã hiện có đã sửa đổi:

#!/usr/bin
def bubble_sort(items):
    changes = passes = 0
    last = len(items)
    swapped = True

    while swapped:
        swapped = False
        passes += 1
        for j in range(1, last):
            if items[j - 1] > items[j]:
                items[j], items[j - 1] = items[j - 1], items[j]  # Swap
                changes += 1
                swapped = True
                last = j


    print(items)
    print("Number of passes =",passes)
    print("Number of swaps =",changes)


print("Welcome to a Bubble Sort Algorithm in Python!")

while True:
    print("Enter as many numbers as you want.\n You can choose between 0 and 9.\nLeave a space between each one")
    numbers = input()
    items = [int(num) for num in numbers.split() if num.isdigit()]
    if items: bubble_sort(items)

Đã trả lời ngày 15 tháng 12 năm 2014 lúc 20:27Dec 15, 2014 at 20:27

Hướng dẫn bubble sort in python with user input - sắp xếp bong bóng trong python với đầu vào của người dùng

smac89smac89smac89

36.1K14 Huy hiệu vàng117 Huy hiệu bạc166 Huy hiệu đồng14 gold badges117 silver badges166 bronze badges

4

def b_sort(list):

for iter_num in range(len(list)-1,0,-1):
    for idx in range(iter_num):

        if list[idx] > list[idx+1]:
            temp = list[idx]
            list[idx] = list[idx+1]
            list[idx+1] = temp

str_input= input("Enter numbers:  ")
list = [int(x) for x in str_input.split()]

b_sort(list)
print('sorted elements are: ')
print(list)

Hướng dẫn bubble sort in python with user input - sắp xếp bong bóng trong python với đầu vào của người dùng

Nimishan

1.2593 huy hiệu vàng19 Huy hiệu bạc29 Huy hiệu đồng3 gold badges19 silver badges29 bronze badges

Đã trả lời ngày 3 tháng 10 năm 2018 lúc 6:31Oct 3, 2018 at 6:31

def sort():
    try:
        n = [1,8,6]
        l = len(n)
        print("Original list:", n)
        for i in range(l - 1):
            for j in range(0,l - i - 1):
                if n[j] > n[j + 1]:
                    n[j], n[j + 1] = n[j + 1], n[j]
        print("List after sorting is:", n)
    except:
        print("Error in inputing values")


sort()

Hướng dẫn bubble sort in python with user input - sắp xếp bong bóng trong python với đầu vào của người dùng

Steve

211K22 Huy hiệu vàng227 Huy hiệu bạc283 Huy hiệu Đồng22 gold badges227 silver badges283 bronze badges

Đã trả lời ngày 9 tháng 12 năm 2020 lúc 13:46Dec 9, 2020 at 13:46

1