缘由
由于一道题需要使用这个方法处理,题目:
输入n 个整数,输出其中最小的k 个。
例如输入1,2,3,4,5,6,7 和8 这8 个数字,则最小的4 个数字为1,2,3 和4。
该算法,即RANDOMIZED-SELECT算法,可以以时间复杂度为O(n)的要求完成。
我不打算证明,需要看证明的请
例如输入1,2,3,4,5,6,7 和8 这8 个数字,则最小的4 个数字为1,2,3 和4。
该算法,即RANDOMIZED-SELECT算法,可以以时间复杂度为O(n)的要求完成。
我不打算证明,需要看证明的请
此外,该题其他的解法请看:
原理
算法导论一书是:
Introduction to Algorithms Third Edition(已上传网盘),其第二版的中文版广为人知:
算法导论
Quicksort
必须先简单的讲一下快速排序,因为RANDOMIZED-SELECT排序需要使用到快速排序。
直接看书上是如何讲解快速排序的:
(摘自7.1 Description of quicksort)
Quicksort, like merge sort (归并排序), applies the divide-and-conquer paradigm introduced in Section 2.3.1. Here is the three-step divide-and-conquer process for sorting a
typical subarray A[p...r]:
直接看书上是如何讲解快速排序的:
(摘自7.1 Description of quicksort)
Quicksort, like merge sort (归并排序), applies the divide-and-conquer paradigm introduced in Section 2.3.1. Here is the three-step divide-and-conquer process for sorting a
typical subarray A[p...r]:
- Divide: Partition (rearrange,后一个词中文上更好理解) the array A[p...r] into two (possibly empty) subarrays A[p...q-1] and A[q+1..r] such that each element of A[p...q-1] is less than or equal to A[q], which is, in turn, less than or equal to each element of A[q+1..r]. Compute the index q as part of this partitioning procedure.
- Conquer: Sort the two subarrays A[p...q-1] and A[q+1..r] by recursive calls
- Combine: Because the subarrays are already sorted, no work is needed to combine them: the entire array A[p...r] is now sorted.
我认为可以强调几点:
- 基本思路就是选择一个元素作为中心,然后将比这个数小的元素放在这个中心的左边,比这个数大的元素放在这个中心的右边,然后对中心左边和右边的两个数组再递归调用快排算法。
- 中心一旦确定了左右两边的数,它