我试图实施quicksort。我写的程序适用于某些列表,但在某些列表中,我似乎在三个while循环之间得到了无限循环。 "在三个while循环之间"意思是它的意思;它是内在的一个,有时是它;它是外层的一个。我哪里弄错了?感谢
def quick_sort_over(array):
print "Original array: ", array
quick_sort(array, 0, len(array) - 1)
def quick_sort(array, start, end):
if start >= end:
return
else:
partition_point = partition(array, start, end)
quick_sort(array, start, partition_point - 1)
if partition_point != end:
quick_sort(array, partition_point + 1, end)
def partition(array, start, end):
print "|start: ", start, "||end: ", end
part_val = array[start]
left_ptr = start + 1
right_ptr = end
while right_ptr > left_ptr:
while right_ptr > left_ptr and array[left_ptr] < part_val:
print "left ptr: ", left_ptr, "right ptr: ", right_ptr
left_ptr += 1
while right_ptr > left_ptr and array[right_ptr] > part_val:
print "left ptr: ", left_ptr, "right ptr: ", right_ptr
right_ptr -= 1
temp = array[left_ptr]
array[left_ptr] = array[right_ptr]
array[right_ptr] = temp
if array[start] > array[left_ptr]:
temp = array[start]
array[start] = array[left_ptr]
array[left_ptr] = temp
if left_ptr == start + 1:
left_ptr = start
print "array has been altered to: ", array
print "returning: ", left_ptr
return left_ptr
array = [9, 1, 8, 2, 7, 3, 6, 4, 6, 5, 34, 4, 56, 4, 3]
quick_sort_over(array)
print array