@@ -524,31 +524,32 @@ private Node ceiling(Node x, Key key) {
524
524
}
525
525
526
526
/**
527
- * Return the key in the symbol table whose rank is {@code k}.
528
- * This is the (k+1)st smallest key in the symbol table.
527
+ * Return the key in the symbol table of a given {@code rank}.
528
+ * This key has the property that there are {@code rank} keys in
529
+ * the symbol table that are smaller. In other words, this key is the
530
+ * ({@code rank}+1)st smallest key in the symbol table.
529
531
*
530
- * @param k the order statistic
531
- * @return the key in the symbol table of rank {@code k }
532
- * @throws IllegalArgumentException unless {@code k } is between 0 and
532
+ * @param rank the order statistic
533
+ * @return the key in the symbol table of given {@code rank }
534
+ * @throws IllegalArgumentException unless {@code rank } is between 0 and
533
535
* <em>n</em>–1
534
536
*/
535
- public Key select (int k ) {
536
- if (k < 0 || k >= size ()) {
537
- throw new IllegalArgumentException ("argument to select() is invalid: " + k );
537
+ public Key select (int rank ) {
538
+ if (rank < 0 || rank >= size ()) {
539
+ throw new IllegalArgumentException ("argument to select() is invalid: " + rank );
538
540
}
539
- Node x = select (root , k );
540
- return x .key ;
541
+ return select (root , rank );
541
542
}
542
543
543
- // the key of rank k in the subtree rooted at x
544
- private Node select ( Node x , int k ) {
545
- // assert x != null;
546
- // assert k >= 0 && k < size(x) ;
547
- int t = size (x .left );
548
- if (t > k ) return select (x .left , k );
549
- else if (t < k ) return select (x .right , k - t - 1 );
550
- else return x ;
551
- }
544
+ // Return key in BST rooted at x of given rank.
545
+ // Precondition: rank is in legal range.
546
+ private Key select ( Node x , int rank ) {
547
+ if ( x == null ) return null ;
548
+ int leftSize = size (x .left );
549
+ if (leftSize > rank ) return select (x .left , rank );
550
+ else if (leftSize < rank ) return select (x .right , rank - leftSize - 1 );
551
+ else return x . key ;
552
+ }
552
553
553
554
/**
554
555
* Return the number of keys in the symbol table strictly less than {@code key}.
0 commit comments