将快速排序函数的比较计数器添加到他们的寂寞工作中就好了,并在StackOverflow的其他地方广泛介绍,但是当我尝试在我的Quicksort类的实现中添加一个时,比较计数器不起作用。
同样,这篇文章与quicksort比较计数器的主题不同,我试图将它添加到quicksort类。
请忽略有关此问题的non_inplace()
方法。
这是我的比较计数器代码的实现,我认为它应该是。
from random import randint
class QuickSort(object):
'''
Classic quicksort implementation with both non-inplace and
inplace methods presented for educational use.
>>>array = [16, 45, 24, 46, 46, 18, 29, 49, 4, 11]
>>>object = Quicksort(array)
>>>object.non_inplace()
[4, 11, 16, 18, 24, 29, 45, 46, 46, 49]
>>>object.inplace()
[4, 11, 16, 18, 24, 29, 45, 46, 46, 49]
'''
def __init__(self, arr, start=0, stop=None, pindex=0):
self.arr = arr
self.start = start
self.stop = stop
self.pindex = pindex
self.counter = 0
def non_inplace(self):
'''
Non-inplace quicksort implementation
'''
if len(self.arr) <= 1:
return self.arr
left, equal, right = [], [], []
pivot = self.arr[randint(0, len(self.arr) - 1)]
for i in self.arr:
if i < pivot:
left.append(i)
elif i == pivot:
equal.append(i)
else: # i > pivot
right.append(i)
left = QuickSort(left)
right = QuickSort(right)
return left.non_inplace() + equal + right.non_inplace()
def partition(self):
if not (self.start <= self.pindex <= self.stop):
raise ValueError('Pivot Index must be between Start and Stop')
self.arr[self.start], self.arr[self.pindex] = self.arr[self.pindex], self.arr[self.start]
pivot = self.arr[self.start]
i = self.start + 1
j = self.start + 1
while j <= self.stop:
if self.arr[j] <= pivot:
self.arr[j], self.arr[i] = self.arr[i], self.arr[j]
i += 1
self.counter += 1
j += 1
self.arr[self.start], self.arr[i - 1] = self.arr[i - 1], self.arr[self.start]
return i - 1
def inplace(self):
if self.stop is None:
self.stop = len(self.arr) - 1
self.count += 1
if self.stop - self.start < 1:
return
self.pindex = randint(self.start, self.stop)
i = QuickSort(self.arr, self.start, self.stop, self.pindex).partition()
#print(self.arr, i, self.pindex)
QuickSort(self.arr, self.start, i-1).inplace()
QuickSort(self.arr, i+1, self.stop).inplace()
return self.arr
感谢您的意见和建议。