给定一个数组A,寻找第k大的数字。
本质上是查询操作,但是却使用到快排思想(即分治)
A = [-1, 3, -2, 4, -5];
def partition(A: int, low: int, high: int) -> int:
temp = A[low];
while low < high:
while low < high and temp >= A[high]:
high -= 1;
A[low] = A[high];
while low < high and temp < A[low]:
low += 1;
A[high] = A[low];
A[low] = temp;
return low;
def quciksort(A: int, low: int, high: int, k: int) -> int:
if low <= high:
pos = partition(A, low, high);
if pos == k - 1:
return A[pos];
elif pos > k - 1:
return quciksort(A, low, pos-1, k);
elif pos < k - 1:
return quciksort(A, pos+1, high, k);
else:
return -1;
print(quciksort(A, 0, len(A)-1, 5));