Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we find the i'th greatest element of the array?

Tags:

c

algorithm

Algorithm for Finding nth smallest/largest element in an array using data strucuture self balancing binary search tree..

Read the post: Find kth smallest element in a binary search tree in Optimum way. But the correct answer is not clear, as i am not able to figure out the correct answer, for an example that i took...... Please a bit more explanation required.......

like image 342
AGeek Avatar asked Dec 07 '22 02:12

AGeek


1 Answers

C.A.R. Hoare's select algorithm is designed for precisely this purpose. It executes in [expected] linear time, with logarithmic extra storage.

Edit: the obvious alternative of sorting, then picking the right element has O(N log N) complexity instead of O(N). Storing the i largest elements in sorted order requires O(i) auxiliary storage, and roughly O(N * i log i) complexity. This can be a win if i is known a priori to be quite small (e.g. 1 or 2). For more general use, select is usually better.

Edit2: offhand, I don't have a good reference for it, but described the idea in a previous answer.

like image 144
Jerry Coffin Avatar answered Dec 27 '22 22:12

Jerry Coffin