【发布时间】:2016-01-31 07:31:00
【问题描述】:
我有一个文本文件“result.txt”。以下代码打开 result.txt 并将其内容读入列表“数据”。之后,定义函数“partition”,然后定义递归函数“quicksort”。最后,将函数快速排序应用于列表数据。
import io
with io.open('result.txt', encoding='latin-1') as myfile:
data = myfile.readlines()
def partition(list, start, end):
pivot = list[end] # Partition around the last value
bottom = start-1 # Start outside the area to be partitioned
top = end # Ditto
done = 0
while not done: # Until all elements are partitioned...
while not done: # Until we find an out of place element...
bottom = bottom+1 # ... move the bottom up.
if bottom == top: # If we hit the top...
done = 1 # ... we are done.
break
if list[bottom] > pivot: # Is the bottom out of place?
list[top] = list[bottom] # Then put it at the top...
break # ... and start searching from the top.
while not done: # Until we find an out of place element...
top = top-1 # ... move the top down.
if top == bottom: # If we hit the bottom...
done = 1 # ... we are done.
break
if list[top] < pivot: # Is the top out of place?
list[bottom] = list[top] # Then put it at the bottom...
break # ...and start searching from the bottom.
list[top] = pivot
# Put the pivot in its place.
return top # Return the split point
def quicksort(list, start, end):
if start < end: # If there are two or more elements...
split = partition(list, start, end) # ... partition the sublist...
quicksort(list, start, split-1)
quicksort(data, 0, (int(len(data))-1))
快速排序无法对数据进行排序。打印数据[500500] 返回“scheinhei”,而打印数据[500501] 返回“blasende”。它没有按我想要的字母顺序排序。被排序的数据包括符号、数字和字母。我怎样才能让这种快速排序起作用?
【问题讨论】:
-
你做了什么来调试它?例如用 2 个字符的字符串进行测试?单独测试
partitiofn? -
不要命名变量
list!与任何问题完全无关,但是当您隐藏内置名称时,您只是在为令人困惑的错误做好准备。 -
我没有时间深入研究算法,但我保证你不会尝试做
list[top] = list[bottom]。您是否尝试交换这两个值? -
@ATLUS 这太荒谬了。他不是在问如何对列表进行排序,而是在问如何实现快速排序。如果你想滚动,你不需要重新发明轮子,但你确实需要重新发明轮子来学习向心运动......
-
你重新发明了轮子,因为你正在参加 Wheel Reinvention 101。