跳至主要内容

Kth Problem (Selection Problem)

Kth Problem (Selection Problem)

Begin with a problem

“compare six times to find the third small number of five numbers”

Analysis process:

  1. First, come up with the solution of sorting

    • Using the sort by comparison cost O(nlog2n)O(n\log_2n), like quicksort or mergesort;
    • then choose the one with constant time;
    • but it’s not good enough for this problem
  2. The second thought: Try blindly – 7 times in the worst case

  3. The third one: realize the differences between “find the k th small number” between sort:

    • when to find the k-th small number, we don’t need to know the order of other numbers, so if we sort them, we will do many useless work.
  4. The forth one: realize the “find the k th small number” and sort are similar in essence

    • If we deem sorting as cancel the possibility like Knuth1 said (choosing a permutation of the input), the k-th small number is also choose some permutations of the input.

Abstraction of problem

A demonstration

The following graph is the demonstration of above problem:

Selection Problem

Description

  • We just want the third number, so which one is the first or second may not be a must. Try to avoid useless order so as to save comparison.
  • More generally, we only have to know the one larger than (k1)(k-1) elements, smaller than (nk)(n-k) elements. So the lower bound of this problem is O(n)O(n)

Perspective one – rule out more possibilities

Introduction

As we have mentioned, the problem can be seen as the process of ruling out possibilities of permutations.

suppose an array aa of length n :a1,a2,...,an: a_1, a_2, ... , a_n

If we choose two numbers at random to compare and get the following result:

ai<aja_i < a_j : (Any) comparison result can exclude half possibilities of all permutations of array a

Then, if we compare aia_i or (aja_j) with the third element (ama_m), the third element has three possible locations:

here aia_i here aja_j here

but compare with any of aia_i or aja_j, we can exclude 1/31/3 or 2/32/3 possibilities, so on so forth. And this process is shown in decision tree model of comparison sort 2.

Decision Tree

We can conclude that by one comparison, excluding 1/21/2 possibilities is the best case.

Application – make use of 121 \over 2

  1. Compare different elements
    Taking the problem we mentioned at the beginning of the article as an example.
    Basic:
    • Five numbers: 5!5! possibilities
    • the middle one is settled: 2!2!2! * 2! possibilities are accepted: so there is 30=5!/430 = 5! / 4 possibilities to exclude.

Since we have the principle, through some trial and error, we can come up with the following approach to solve the problem. (one tricky step is to ignore the smallest one of 4 number – ie, A and B, for it can’t be the median)

Median of Five

> the possibilities remaining after every comparison:  
> $1/2 * 1/2 * 3/5 * 1/2 * 3/5 * 2/3$
  1. Method like quicksort – choose a good pivot
    Before we dive into this solution, let’s study why quick-sort is so fast and why a good pivot can be very important for quicksort.

Basic:

  • the critical procedure of quicksort – partition: choose a pivot and compare other elements with pivot.
    In the following graph, the pivot A is very good for the elements is separated evenly around it, so if you compare it with one more element it will rule out 50%50\% possibilities. On the other hand, the pivot B is very bad and one more comparison can only rule out 1(2n+1)1\over(2n+1) possibilities in worse case.

Pivot
Analysis:
on average, the pivot is not as good as pivot A but also as bad as pivot B, so quick-sort can have a recursion tree whose height is proportional to log2nlog_2n. And the better the pivot is, the less the recursions happen, the faster the sort proceeds.



**To be continued **

Perspective two – Save some comparison results

Tournament Tree (Winner Tree)

Heap

More

Using a way like linear sort?

Reference

  1. Order statistic
  2. 数学之美番外篇:快排为什么那样快

Written with StackEdit.


  1. Donald Knuth. The Art of Computer Programming, Volume 3: Sorting and Searching, Second Edition. Addison-Wesley, 1997. ISBN 0-201-89685-0. Chapter Five - Sorting ↩︎

  2. Cormen, Thomas H.; Leiserson, Charles E.; Rivest, Ronald L.; Stein, Clifford (2001). “8 Sorting in Linear Time”. Introduction to Algorithms (3rd ed.). MIT Press & McGraw-Hill. ISBN 0-262-03293-7. ↩︎

评论

此博客中的热门博文

Spring Boot: Customize Environment

Spring Boot: Customize Environment Environment variable is a very commonly used feature in daily programming: used in init script used in startup configuration used by logging etc In Spring Boot, all environment variables are a part of properties in Spring context and managed by Environment abstraction. Because Spring Boot can handle the parse of configuration files, when we want to implement a project which uses yml file as a separate config file, we choose the Spring Boot. The following is the problems we met when we implementing the parse of yml file and it is recorded for future reader. Bind to Class Property values can be injected directly into your beans using the @Value annotation, accessed via Spring’s Environment abstraction or bound to structured objects via @ConfigurationProperties. As the document says, there exists three ways to access properties in *.properties or *.yml : @Value : access single value Environment : can access multi

Elasticsearch: Join and SubQuery

Elasticsearch: Join and SubQuery Tony was bothered by the recent change of search engine requirement: they want the functionality of SQL-like join in Elasticsearch! “They are crazy! How can they think like that. Didn’t they understand that Elasticsearch is kind-of NoSQL 1 in which every index should be independent and self-contained? In this way, every index can work independently and scale as they like without considering other indexes, so the performance can boost. Following this design principle, Elasticsearch has little related supports.” Tony thought, after listening their requirements. Leader notice tony’s unwillingness and said, “Maybe it is hard to do, but the requirement is reasonable. We need to search person by his friends, didn’t we? What’s more, the harder to implement, the more you can learn from it, right?” Tony thought leader’s word does make sense so he set out to do the related implementations Application-Side Join “The first implementation

Implement isdigit

It is seems very easy to implement c library function isdigit , but for a library code, performance is very important. So we will try to implement it and make it faster. Function So, first we make it right. int isdigit ( char c) { return c >= '0' && c <= '9' ; } Improvements One – Macro When it comes to performance for c code, macro can always be tried. #define isdigit (c) c >= '0' && c <= '9' Two – Table Upper version use two comparison and one logical operation, but we can do better with more space: # define isdigit(c) table[c] This works and faster, but somewhat wasteful. We need only one bit to represent true or false, but we use a int. So what to do? There are many similar functions like isalpha(), isupper ... in c header file, so we can combine them into one int and get result by table[c]&SOME_BIT , which is what source do. Source code of ctype.h : # define _ISbit(bit) (1 << (