使用python bubble sort对用户输入的数字列表进行排序

时间:2014-12-15 20:24:58

标签: python-3.x bubble-sort

我刚刚开始学习python,我决定尝试进行冒泡排序。如果要排序的数字是0到9,我使用下面的代码可以正常工作。之后,它没有正确排序。我认为,在我有限的知识中,这是因为它是一个'列表'。

我希望用户能够输入数字,但程序可以对它们进行排序,而不管数字的长度。任何帮助将不胜感激。

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

4 个答案:

答案 0 :(得分:2)

试试这个:

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)  

答案 1 :(得分:0)

尝试map

我之前建议使用map,但我只记得python 3.x *中的map会生成一个生成器而不是一个列表,所以这就是为什么你不能使用它的长度。更新后的答案如下

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

修改现有代码:

#!/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)

答案 2 :(得分:0)

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)

答案 3 :(得分:0)

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()
相关问题