Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Suitable data structure for search interval [duplicate]

Possible Duplicate:
Does an open-ended interval implementation exist for Java?

I'm new to Java and i would like to know what is the best data structure and how can i search through that data structure for my case: I have int intervals eg: 10-100, 200-500, 1000-5000 and for each interval i have a value 1, 2, 3, 4. I would like to know how can i save all those intervals and their values in a data structure and how can i search through that data structure to return the value for the specific interval. Eg. if i search 15, that is in interval 10-100, i would like to return 1.

Thank you

like image 774
Ionut Bogdan Avatar asked Dec 06 '12 11:12

Ionut Bogdan


People also ask

Which data structure is best for searching in Java?

Linear Search Algorithm in Java Linear search or sequential search is the simplest search algorithm.

Which data structure prevents duplicates?

HashSet, LinkedHashSet and TreeSet are the implementations of Set interface which does not allow duplicate elements.

Which of the following data structures can have duplicate?

a List object can contain duplicate elements.

What is Interval search in data structure?

In computer science, an interval tree is a tree data structure to hold intervals. Specifically, it allows one to efficiently find all intervals that overlap with any given interval or point.


1 Answers

Use TreeMap, which is NavigableMap (Java 6 or higher).

Suppose you have entries key->value (10->1, 100->1, 200->2, 500->2, 1000->3, 5000->3)

floorEntry(15) will return 10->1

ceilingEntry(15) will return 100->1

With this you can determine the interval number of 15, which is 1. You can also determine if a number is between intervals.

Edit: added example

    TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
    map.put(10, 1);
    map.put(100, 1);
    map.put(200, 2);
    map.put(500, 2);
    map.put(1000, 3);
    map.put(5000, 3);
    int lookingFor = 15;
    int groupBelow = map.floorEntry(lookingFor).getValue();
    int groupAbove = map.ceilingEntry(lookingFor).getValue();
    if (groupBelow == groupAbove) {
        System.out.println("Number " + lookingFor + " is in group " + groupBelow);
    } else {
        System.out.println("Number " + lookingFor + 
                " is between groups " + groupBelow + " and " + groupAbove);
    }
like image 125
RokL Avatar answered Nov 16 '22 22:11

RokL