from tools import cost_time
def quick1(data: list):
lower = []
equal = []
higher = []
if len(data) > 1:
pivot = data[0]
for x in data:
if x > pivot:
higher.append(x)
elif x < pivot:
lower.append(x)
else:
equal.append(x)
return quick1(lower) + equal + quick1(higher)
else:
return data
def partition(data: list, first, last):
pivot_value = data[first]
left_mark = first
right_mark = last
while left_mark < right_mark:
while left_mark < right_mark:
if data[right_mark] < pivot_value:
data[left_mark] = data[right_mark]
break
else:
right_mark -= 1
while left_mark < right_mark:
if data[left_mark] >= pivot_value:
data[right_mark] = data[left_mark]
break
else:
left_mark += 1
data[left_mark] = pivot_value
return left_mark
def partition2(data: list, first, last):
pivot_value = data[first]
low = first
high = last
while low < high:
while low < high and data[high] >= pivot_value:
high -= 1
data[low] = data[high]
while low < high and data[low] < pivot_value:
low += 1
data[high] = data[low]
data[low] = pivot_value
return low
def quick_helper(data: list, first, last):
if first < last:
split_point = partition2(data, first, last)
quick_helper(data, first, split_point - 1)
quick_helper(data, split_point + 1, last)
def quick2(data: list):
first = 0
last = len(data) - 1
quick_helper(data, first, last)
python 实现快速排序
最新推荐文章于 2023-03-21 10:33:23 发布