TopK.java

public class TopK {
 
    private int [] buffer;
    private int k;
    private int len;
 
    public TopK(int sk) {
        k = sk;
        len = 0;
        buffer = new int[k];
    }
 
    public int getNumKept() { return len; }
 
    public int get(int i) { return buffer[i]; }
 
    public void add(int x) {
        if(k==0)
            return;
        if(len<k) {
            buffer[len] = x;
            len++;
        } else {
            int min = buffer[0], mi = 0;
            for(int i = 1; i<len; i++)
                if(buffer[i]<min) {
                    min = buffer[i];
                    mi = i;
                }
            if(min<x) {
                buffer[mi] = x;
            }
        }
    }
}
software_testing/lect03_topk.txt · Last modified: 2008/11/13 17:55 (external edit)
 
 
©2008 Another cool website by 80KV