[英]can anyone tell what's the bug in my quick sort code
誰能說出我的快速排序算法中的錯誤? 我使用兩點“左”和“右”與數據透視表進行比較,並且當nums [left]> nums [right]時交換nums [left]和nums [right]。 當左索引大於右索引時,中斷並交換nums [left]和nums [piovt],返回左索引。
nums = [3,2,3,1,2,4,5,5,6]
n = len(nums)
def partition(nums,left,right,pivot):
while left<right:
if left<right and nums[left]<=nums[pivot]:
left += 1
if left<right and nums[right]>=nums[pivot]:
right -= 1
elif nums[left]>nums[right]:
nums[left],nums[right] = nums[right],nums[left]
left += 1
right -= 1
nums[left],nums[pivot] = nums[pivot],nums[left]
return left
def quicksort(nums,low,high,pivot):
if low<high:
pos = partition(nums,low,high,pivot)
quicksort(nums,low,pos-2,pos-1)
quicksort(nums,pos+1,high-1,high)
return nums
quicksort(nums,0,n-2,n-1)
print(nums)
回答:[1、2、2、3、3、5、5、6、4]
若要獲取數組的中間索引,應將quicksort的軸設置為整數n / 2。
這是您代碼中的幾個錯誤,我已經為您重寫了代碼。 您可以參考注釋並進行一些測試以找出答案。
import random
# two pointers solution, choose the last one as pivot
def partition(nums, left, right, pivot):
while left < right:
# here should change < to <=, because if pivot is larger than all in nums[left:right+1], should swap nums[left] with nums[pivot]
# here I change if to while, because you should traverse the pointer to find the place which is invalid in partition
while left <= right and nums[left] <= nums[pivot]:
left += 1
# here I change if to while, same reason above
while left < right and nums[right] > nums[pivot]:
right -= 1
# you should not use elif here, because you have two ifs, the first if does not work here
if left < right:
nums[left], nums[right] = nums[right], nums[left]
nums[left], nums[pivot] = nums[pivot], nums[left]
return left
def quicksort(nums, low, high, pivot):
if low < high:
pos = partition(nums, low, high, pivot)
quicksort(nums, low, pos - 2, pos - 1)
# here is another problem: notice that nums[pivot] is the last element, not the nums[high]
quicksort(nums, pos + 1, high, high + 1)
return nums
if __name__ == '__main__':
for _ in range(100):
nums = [random.randrange(1, 100) for _ in range(10000)]
n = len(nums)
if sorted(nums) != quicksort(nums, 0, n - 2, n - 1):
print('incorrect')
print('success')
我已盡力幫助您,希望您喜歡它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.