Internal Sorting: Quicksort-2: Sorting by Exchanging

本文详细介绍了快速排序算法,包括动画演示、复杂度分析、算法流程、数据表和Java实现。特别指出,选择中间元素作为枢轴可以提高已排序或相同元素数组的排序效率。
摘要由CSDN通过智能技术生成

Quicksort-2:快速排序-2


Animation

quick sort
Animated visualization of the quicksort algorithm. The horizontal lines are pivot values.


这里写图片描述
Full example of quicksort on a random set of numbers. The shaded element is the pivot. It is always chosen as the last element of the partition. However, always choosing the last element in the partition as the pivot in this way results in poor performance ( O(n2) ) on already sorted arrays, or arrays of identical elements. Since sub-arrays of sorted / identical elements crop up a lot towards the end of a sorting procedure on a large set, versions of the quicksort algorithm which choose the pivot as the middle element run much more quickly than the algorithm described in this diagram on large sets of numbers.


Complexity

Class Sorting algorithm
Data structure Array
Worst case performance O(n2)
Best case performance O(nlogn) (simple partition) or O(n) (three-way partition and equal keys)
Average case performance O(nlogn)
Worst case space complexity O(n) auxiliary (naive), O(logn) auxiliary (Sedgewick 1978)

Algorithm Q

Algorithm Q (Quicksort). Records R1,...,RN are rearranged in place; after
sorting is complete their keys will be in order, K1<=...<=KN . An auxiliary
stack with at most lgN entries is needed for temporary storage. This algorithm
follows the quicksort partitioning procedure described in the text above, with
slight modifications for extra efficiency:
a) We assume the presence of artificial keys K0= and KN+1=+ such
that

K0<=Ki<=KN+1 for 1<=i<=N . (13)

(Equality is allowed.)
b) Subfiles of M or fewer elements are left unsorted until the very end of the
procedure; then a single pass of straight insertion is used to produce the final
ordering. Here M>=1 is a parameter that should be chosen as described in
the text below. (This idea, due to R. Sedgewick, saves some of the overhead
that would be necessary if we applied straight insertion directly to each small
subfile, unless locality of reference is significant.)
c) Records with equal keys are exchanged, although it is not strictly necessary
to do so. (This idea, due to R. C. Singleton, keeps the inner loops fast and
helps to split subfiles nearly in half when equal elements are present; see
exercise 18.)
Q1. [Initialize.] If N<

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值