[英]Python Quicksort algorithm is sorting incorrectly
As the title reads, I'm having encountering an error with my Python Quicksort code.如标题所述,我的 Python 快速排序代码遇到错误。 My code is further below and this is the input file that I'm using to test.
我的代码在下面,这是我用来测试的输入文件。
5
3
8
6
7
4
9
2
1
10
In the code, the variable i
is the border value and the variable j
is the current value being compared to the pivot.在代码中,变量
i
是边界值,变量j
是与 pivot 进行比较的当前值。 The issue is that when Partition
executes its first iteration, the value 3
in the array doesn't end up on the left side of the pivot value ( 5
in this case) as it should.问题在于,当
Partition
执行其第一次迭代时,数组中的值3
并没有按照应有的方式出现在 pivot 值(在本例中为5
)的左侧。 I'm always using the leftmost index as the pivot by the way.顺便说一句,我总是使用最左边的索引作为 pivot。
def Partition(input_array, left_index, right_index):
pivot_value = input_array[left_index]
i = left_index + 1
for j in range(i+1, right_index):
if input_array[j] < pivot_value:
swap(input_array, i, j)
i = i + 1
swap(input_array, left_index, i - 1)
print(input_array)
return i - 1
def swap(input_array, i, j):
input_array[i], input_array[j] = input_array[j], input_array[i]
return input_array
This is the array before the first iteration of Partition
:这是
Partition
第一次迭代之前的数组:
5, 3, 8, 6, 7, 4, 9, 2, 1, 10
This is the array after the first iteration of Partition
:这是
Partition
第一次迭代后的数组:
1, 4, 2, 5, 7, 3, 9, 8 , 6, 10
As you can see, the 3
is in the incorrect spot.如您所见,
3
位于不正确的位置。 Any help with this would be appreciated!对此的任何帮助将不胜感激!
When you start for j
loop from i+1
index, algorithm does not discover that 3<5
and does not advance i
index.当您从
i+1
索引开始for j
循环时,算法不会发现3<5
并且不会推进i
索引。 Remove +1
移除
+1
Refer to Lomuto scheme here在此处参考 Lomuto 方案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.