最近我试图在Python中实现quicksort算法,但我无法使其正常工作。即使程序对子数组进行排序,它也不会反映在主列表中。我是编程的新手,所以任何人都可以帮助我理解我做的不正确的部分或概念吗?
def swap(arr, right, left):
temp = arr[right]
arr[right] = arr[left]
arr[left] = temp
def split_array(arr, right):
left_half = arr[:right]
right_half = arr[right:]
a = (left_half, right_half)
return a
def quick_sort(arr):
if len(arr) >= 2:
pivot = 0
left_mark = pivot + 1
right_mark = len(arr) - 1
stop = True
while stop:
while arr[pivot] > arr[left_mark] and left_mark < right_mark:
left_mark += 1
while arr[pivot] < arr[right_mark] and left_mark < right_mark:
right_mark -= 1
if left_mark < right_mark:
swap(arr, right_mark, left_mark)
right_mark -= 1
left_mark += 1
else:
if arr[pivot] > arr[right_mark]:
swap(arr, right_mark, pivot)
stop = False
left, right = split_array(arr, right_mark)
quick_sort(left)
quick_sort(right)
return arr
array = [8, 6, 1, 7, 0, 5, 4, 3, 2, 1]
print(quick_sort(array))
答案 0 :(得分:2)
改变这个:
left, right = split_array(arr, right_mark)
quick_sort(left)
quick_sort(right)
到此:
left, right = split_array(arr, right_mark)
arr = quick_sort(left) + quick_sort(right)
Quicksort通常实施&#34;就地&#34;避免复制数组。您的实现会在每一步创建一个完整的数组副本并返回它,因此您需要自己重新组装这些部分。
<强>更新强>
进行小规模更改以使您的算法就位:
def quick_sort(arr, start=0, end=None):
if end is None: end = len(arr)-1
if end > start:
pivot = start
left_mark = start + 1
right_mark = end
stop = True
while stop:
while arr[pivot] > arr[left_mark] and left_mark < right_mark:
left_mark += 1
while arr[pivot] < arr[right_mark] and left_mark < right_mark:
right_mark -= 1
if left_mark < right_mark:
swap(arr, right_mark, left_mark)
right_mark -= 1
left_mark += 1
else:
if arr[pivot] > arr[right_mark]:
swap(arr, right_mark, pivot)
stop = False
quick_sort(arr, start, right_mark - 1)
quick_sort(arr, right_mark, end)
array = [8, 6, 1, 7, 0, 5, 4, 3, 2, 1]
quick_sort(array) # in-place
print(array) # now sorted
IMO,以下内容更清晰,更符合该算法的典型描述:
def quick_sort(arr, start=0, end=None):
if end is None:
end = len(arr) - 1
if end <= start:
return
pivot = arr[start]
left_mark = start - 1
right_mark = end + 1
while left_mark < right_mark:
left_mark += 1
while arr[left_mark] < pivot:
left_mark += 1
right_mark -= 1
while arr[right_mark] > pivot:
right_mark -= 1
if left_mark < right_mark:
arr[left_mark], arr[right_mark] = arr[right_mark], arr[left_mark]
quick_sort(arr, start, right_mark)
quick_sort(arr, right_mark + 1, end)
答案 1 :(得分:0)
你是完全正确的! left
和right
是split_array
之后的单独实体,而不是原始arr
的部分内容。在quick_sort(right)
之后,请说arr=left+right
。我认为会这样做。 (当left
或right
中只有一个元素时,需要检查案例。)