用BST实现
package Sorting_Searching;
import CtCILibrary.AssortedMethods;
/**
* Imagine you are reading in a stream of integers. Periodically, you wish to be
* able to look up the rank of a number x (the number of values less than or
* equal to x). Implement the data structures and algorithms to support these
* operations. That is, implement the method track(int x), which is called
* when each number is generated, and the methodgetRankOfNumber (int x), which
* returns the number of values less than or equal to x (not including x
* itself).
*
* EXAMPLE
Stream (in order of appearance): 5, 1, 4, 4, 5, 9, 7, 13, 3
getRankOfNumber(l) = 0
getRankOfNumber(3) = 1
getRankOfNumber(4) = 3
* 不断地读入数字流,要求实现track和getRankOfNumber方法。
*
*/
public class S11_8 {
private static RankNode root = null;
// track就是插入BST的过程
public static void track(int number) {
if (root == null) {
root = new RankNode(number);
} else {
root.insert(number);
}
}
// 得到rank就是得到有多少个比number小
public static int getRankOfNumber(int number) {
return root.getRank(number);
}
public static void main(String[] args) {
int size = 5;
int[] list = AssortedMethods.randomArray(size, -10, 10);
for (int i = 0; i < list.length; i++) {
track(list[i]);
}
int[] tracker = new int[size];
for (int i = 0; i < list.length; i++) {
int v = list[i];
int rank1 = root.getRank(list[i]);
tracker[rank1] = v;
}
for (int i = 0; i < tracker.length - 1; i++) {
if (tracker[i] != 0 && tracker[i + 1] != 0) {
if (tracker[i] > tracker[i + 1]) {
System.out.println("ERROR at " + i);
}
}
}
// System.out.println("Array: " + AssortedMethods.arrayToString(list));
// System.out.println("Ranks: " + AssortedMethods.arrayToString(tracker));
for(int i : list){
System.out.println(i + ": " + getRankOfNumber(i));
}
}
static class RankNode {
public int left_size = 0;
public RankNode left;
public RankNode right;
public int data = 0;
public RankNode(int d) {
data = d;
}
public void insert(int d) {
if (d <= data) {
if (left != null) {
left.insert(d);
} else {
left = new RankNode(d);
}
left_size++;
} else {
if (right != null) {
right.insert(d);
} else {
right = new RankNode(d);
}
}
}
public int getRank(int d) {
if (d == data) {
return left_size;
} else if (d < data) {
if (left == null) {
return -1;
} else {
return left.getRank(d);
}
} else {
int right_rank = right == null ? -1 : right.getRank(d);
if (right_rank == -1) {
return -1;
} else {
return left_size + 1 + right_rank;
}
}
}
}
}

本文介绍了一种使用二叉搜索树(BST)实现排名查找算法的方法,通过track和getRankOfNumber方法来实时更新和获取数字排名。
143

被折叠的 条评论
为什么被折叠?



