Class TopNBuffer
java.lang.Object
gaiasky.util.TopNBuffer
A fixed-capacity data structure that maintains the top N elements by value, where N is defined by the buffer capacity.
Each element is represented by a pair consisting of an index and a value. When a new element is added, the structure
checks if it has reached capacity. If not, the new element is simply added. If the buffer is full, the element with
the current maximum value is identified. If the new element's value is smaller than the maximum, the maximum element
is removed, and the new element is inserted in its place. Otherwise, the new element is discarded.
This structure is useful in scenarios where only the smallest N elements need to be retained, such as implementing a top-N filtering algorithm based on value.
-
Constructor Summary
ConstructorsConstructorDescriptionTopNBuffer(int capacity) Constructs a TopNBuffer with the specified capacity. -
Method Summary
Modifier and TypeMethodDescriptionvoidadd(int index, double value) Adds a new element to the buffer.voidclear()Clears the buffer by resetting its size to zero.doublegetValue(int i) Returns the value at the specified index.int[]Returns the array of indices currently in the buffer.intsize()Returns the current number of elements in the buffer.voidsort()Sorts the buffer in ascending order based on the values, maintaining index-value pairs.
-
Constructor Details
-
TopNBuffer
public TopNBuffer(int capacity) Constructs a TopNBuffer with the specified capacity.- Parameters:
capacity- the maximum number of elements the buffer can hold.
-
-
Method Details
-
clear
public void clear()Clears the buffer by resetting its size to zero. -
add
public void add(int index, double value) Adds a new element to the buffer. If the buffer is not full, the element is added. If the buffer is full and the new element's value is smaller than the current maximum value, the maximum element is removed and the new element is inserted in its place.- Parameters:
index- the index associated with the element.value- the value associated with the element.
-
indexArray
public int[] indexArray()Returns the array of indices currently in the buffer.- Returns:
- the indices array.
-
size
public int size()Returns the current number of elements in the buffer.- Returns:
- the number of elements.
-
getValue
public double getValue(int i) Returns the value at the specified index.- Parameters:
i- the index in the buffer.- Returns:
- the value at the specified index.
-
sort
public void sort()Sorts the buffer in ascending order based on the values, maintaining index-value pairs. The sorting algorithm is a dual-pivot quicksort optimized for small fixed-size arrays.
-