[英]Bubble Sort Algorithm in Python - Last Number Not Sorting
The algorithm sorts all the numbers except the first one, and sets it as last. 该算法对除第一个以外的所有数字进行排序,并将其设置为最后一个。 Please help! 请帮忙!
def bubbleSort(numbers): # Bubble Sort Algorithm
numbers = list(numbers)
i = 0
j = 0
for i in range(len(numbers)):
for j in range(len(numbers) - i):
if numbers[j] < numbers[j-1]:
temp = numbers[j-1]
numbers[j-1] = numbers[j]
numbers[j] = temp
print numbers
print numbers
The problem is that sometimes [j-1] becomes negative. 问题是有时[j-1]变为负数。 In python, numbers[-1] means "get the last element in numbers". 在python中,numbers [-1]表示“获取数字中的最后一个元素”。 Here is a fixed version: 这是固定版本:
def bubbleSort(numbers): # Bubble Sort Algorithm
nums = list(numbers)
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if numbers[j] < numbers[i]:
numbers[j], numbers[i] = numbers[i], numbers[j]
print numbers
You'll notice that it is also possible to swap numbers without a temp variable in python as well 您会注意到,在python中也可以在没有临时变量的情况下交换数字
I would not describe this as a 'Bubble sort' as it does not swap the list elements that are next to each other. 我不会将其描述为“气泡排序”,因为它不会交换彼此相邻的列表元素。 Its more like a 'Selection sort' as it is looking through the list and comparing each element with the first then swapping the smallest number with the first. 它更像是一个“选择排序”,因为它要遍历列表并将每个元素与第一个元素进行比较,然后与第一个元素交换最小的数字。
It seems to be a bubble/selection mash-up. 似乎是气泡/选择混搭。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.