@zqbinggong
2018-04-27T16:36:36.000000Z
字数 1490
阅读 1086
快速排序
算法导论
QuickSort(A,p,r)
if p < r
q = Partition(A,p,r)
QuickSort(A,p,q-1)
QuickSort(A,q+1,r)
Partition(A,p,r)——,因为for循环会执行n-1次
x = A[r]
i = p - 1 # i 用来记录某个位置,该位置之后的数,要么比x大,要么for循环还没到它;之前的数一定不大于x
for j = p to r-1
if A[j] <= x
i = i + 1
exchange A[i] with A[j]
exchange A[i+1] with A[r]
return i+1
Randomized-Partition(A,p,r)
i = Random(p,r)
exchange A[r] with A[i]
retrun Partition(A,p,r)
版本1(存在问题,可能会有相同的元素被划分到左边的子数组)
Partition(A,p,r)
i = j = Partition(A,p,r)
while i > 1 and A[i-1] = A[i]
i = i - 1
while j < r and A[j+1] = A[j]
j = j + 1
return i,j
版本2
Partition(A,p,r)
x = A[p]
i = h = p #i到h的位置都是与x相同的数
#找到小于x的数,将该数和A[h+1]以及A[i]三者做互换j->i,h+1->j,i->h+1
for j = p+1 to r
if A[j] < x
y = A[j]
A[j] = A[h+1]
A[h+1] = A[i]
A[i] = y
i = i + 1
h = h + 1
else if A[j] = x
exchange A[h+1] with A[j]
h = h + 1
retrun i,h
Tail-Recursive-Quicksort(A,p,r)
while(p < r)
q = Partition(A,p,r)
#进入较小的子数组,以减少栈深度
if q-p < r-q
TRQ(A,p,q-1)
p = q + 1
else
TRQ(A,q+1,r)
r = q - 1
基本思路:利用7-2中的算法,定义区间的大小关系,随机选取一个区间,将比他小的往左放,大的往右边放,相等的(重叠的)放在中。代码