我一直在钻研各种教程和讨论快速排序和quickselect的文章,但是我对他们的了解还摇摇欲坠。
I've been poring over various tutorials and articles that discuss quicksort and quickselect, however my understanding of them is still shaky.
鉴于这种code结构,我需要能够把握和解释quickselect是如何工作的。
Given this code structure, I need to be able to grasp and explain how quickselect works.
// return the kth smallest item int quickSelect(int items[], int first, int last, int k) { int pivot = partition(items, first, last); if (k < pivot-first) { return quickSelect(items, first, pivot, k); } else if (k > pivot) { return quickSelect(items, pivot+1, last, k-pivot); } else { return items[k]; } }
我需要一些帮助分解成伪code,虽然我还没有具备分区功能code,我想知道会怎样做给出的quickselect功能提供的。
I need a little help with breaking down into pseudo-code, and while I haven't been provided with the partition function code, I'd like to understand what it would do given the quickselect function provided.
我知道如何快速排序工作,只是没有quickselect。我刚才提供的code是我们如何快速格式化选择给予一个例子。
I know how quicksort works, just not quickselect. The code I just provided is an example we were given on how to format quick select.
编辑:纠正code是
int quickSelect(int items[], int first, int last, int k) { int pivot = partition(items, first, last); if (k < pivot-first+1) { //boundary was wrong return quickSelect(items, first, pivot, k); } else if (k > pivot-first+1) {//boundary was wrong return quickSelect(items, pivot+1, last, k-pivot); } else { return items[pivot];//index was wrong } }
Courtesty:@Haitao
Courtesty: @Haitao
推荐答案在快速选择最重要的部分就是分区。因此,让我解释一下,第一。
The important part in quick select is partition. So let me explain that first.
分区快速选择纬透视(无论是随机还是第一个/最后一个元素)。然后,它重新排列的方式,小于枢轴的所有元素都在枢轴的左侧和其他人在右边的列表。然后,它返回透视元素的索引。
Partition in quick select picks a pivot (either randomly or first/last element). Then it rearranges the list in a way that all elements less than pivot are on left side of pivot and others on right. It then returns index of the pivot element.
现在我们在这里发现第k个最小元素。之后的分区情况是:
Now here we are finding kth smallest element. After partition cases are:
更多推荐
QuickSelect算法理解
发布评论