Download code

Jump to: navigation, search

Back to Nth_element_(Java)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

QNth.java

 1 /* The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/Nth_element_(Java)?oldid=15027
14 */
15 
16 import java.util.List;
17 import java.util.ArrayList;
18 import java.util.Collections;
19 
20 public class QNth {
21     public static <T extends Comparable<? super T>> T qnth(List<T> sample, int n) {
22         T pivot = sample.get(0);
23         List<T> below = new ArrayList<T>(),
24                 above = new ArrayList<T>();
25         for (T s : sample) {
26             if (s.compareTo(pivot) < 0)
27                 below.add(s);
28             else if (s.compareTo(pivot) > 0)
29                 above.add(s);
30         }
31         int i = below.size(),
32             j = sample.size() - above.size();
33 
34         if (n < i)       return qnth(below, n);
35         else if (n >= j) return qnth(above, n-j);
36         else             return pivot;
37     }
38 
39     public static void main(String[] args) {
40         int n = 64, mid = 32;
41         List<Double> sample = new ArrayList<Double>();
42         for (int i = 0; i < n; i++)
43             sample.add(Math.random());
44         double partial = qnth(sample, mid);
45         Collections.sort(sample);
46         double sorted = sample.get(mid);
47         System.out.println("" + partial + " " + sorted + " " + (partial == sorted));
48     }
49 }


hijacker
hijacker
hijacker
hijacker