普通快排的两种写法
体现在partition中判断左右指针是否越界
private int partition(T[] nums, int l, int h) {
int i = l, j = h + 1;
T v = nums[l];
while (true) {
while (less(nums[++i], v) && i != h) ;
while (less(v, nums[--j]) && j != l) ;
if (i >= j)
break;
swap(nums, i, j);
}
swap(nums, l, j);
return j;
}
另一种用python写的
def partion(self,nums,le,ri):
if le == ri:
return le
leftmark,rightmark = le+1,ri
while True:
while leftmark <= rightmark and nums[leftmark] <= nums[le]:
leftmark += 1
while rightmark >= leftmark and nums[rightmark] >= nums[le]:
rightmark = rightmark -1
if leftmark > rightmark:
break
nums[leftmark],nums[rightmark] = nums[rightmark],nums[leftmark]
nums[le],nums[rightmark] = nums[rightmark],nums[le]
return rightmark
- 这两种方法都是先在最外层有一个while True,然后内层的while判断不相同
- Java版的是判断,左指针不能越过右边界,右指针不能越过左边界
- python版的判断,左指针不能越过右指针
三向切分
public class ThreeWayQuickSort<T extends Comparable<T>> extends QuickSort<T> {
@Override
protected void sort(T[] nums, int l, int h) {
if (h <= l) {
return;
}
int lt = l, i = l + 1, gt = h;
T v = nums[l];
while (i <= gt) {
int cmp = nums[i].compareTo(v);
if (cmp < 0) {
swap(nums, lt++, i++);
} else if (cmp > 0) {
swap(nums, i, gt--);
} else {
i++;
}
}
sort(nums, l, lt - 1);
sort(nums, gt + 1, h);
}
}
- 这种方法在partition中没有返回每次分割后,首个元素在数组中的应该排列的位置,需要通过迭代,来排序
LeetCode----215
这题可以用python内置的heapq来做,用快速排序的partition思想也能(时间是线性的)
下面放一个用partition做出来的
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
lth = len(nums)
l,r = 0,len(nums)-1
while l<r:
i = self.partion(nums,l,r)
if i == lth-k:
return nums[i]
elif i > lth-k:
r = i-1
else:
l = i+1
return nums[-k]
def partion(self,nums,le,ri):
if le == ri:
return le
leftmark,rightmark = le+1,ri
while True:
while leftmark <= rightmark and nums[leftmark] <= nums[le]:
leftmark += 1
while rightmark >= leftmark and nums[rightmark] >= nums[le]:
rightmark = rightmark -1
if leftmark > rightmark:
break
nums[leftmark],nums[rightmark] = nums[rightmark],nums[leftmark]
nums[le],nums[rightmark] = nums[rightmark],nums[le]
return rightmark