使用二分尋找判斷IP地區區間測試,ip地區
IP地址都是轉換成Long型,每個地區以IP段表示,通過二分尋找判斷IP地址落在哪個段。
package hello;
import java.util.*;
public class datatest {
public static void main(String[] args) throws InterruptedException {
final HashMap<Integer, String> map = new HashMap<Integer, String>();
final String DELIMITER = "\t";
String line = ("1677721616777471澳大利亞");
String[] str = line.split(DELIMITER);
Integer key_begin = Integer.parseInt(str[0].trim());
Integer key_end = Integer.parseInt(str[1].trim());
String country = str[2].trim();
// System.out.println(key_begin+" "+" " +country);
map.put(key_begin, country);
ArrayList<Integer> list = new ArrayList<Integer>();
Integer ip = 16777473;
list.add(16777216);
list.add(16777472);
list.add(16778240);
list.add(16779264);
list.add(16777471);
list.add(16778239);
list.add(16779263);
list.add(16781311);
Collections.sort(list);
System.out.println(list.toString());
// [16777216, 16777471, 16777472, 16778239, 16778240, 16779263, 16779264, 16781311]
int low = 0;
int high = list.size();
int middle;
int value;
while (low <= high) {
middle = (low + high) / 2;
value = list.get(middle);
System.out.println("middle="+middle+" and value="+value);
Thread.sleep(300);
if (ip < list.get(middle)) {
high = middle - 1;
} else if (ip > list.get(middle)) {
low = middle + 1;
System.out.println(high+" "+low);
Thread.sleep(300);
}
}System.out.println(high+" "+list.get(high));
}
}