이진 탐색은 소팅이 안되어 있으니 버그를 뿌린다.
package soul;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class LinearNBinarySearch {
class DataStorage {
int key;
Object data;
public DataStorage(int key, Object data) {
this.key = key;
this.data = data;
}
}
DataStorage[] table = new DataStorage[100];
int n = 0;
public void add(int key, Object data) {
table[n++] = new DataStorage(key, data);
}
public Object linearSearch(int key) {
int i;
i = 0;
while (i < n) {
if (table[i].key == key)
return (table[i].data);
i++;
}
return null;
}
public Object binarySearch(int key) {
//must be sorted.
int low, high, middle;
low = 0;
high = n - 1;
while(low <= high) {
middle = (low + high) / 2;
if(key == table[middle].key)
return table[middle].data;
else if(key < table[middle].key)
high = middle - 1;
else low = middle + 1;
}
return null;
}
public static void main(String args[]) {
LinearNBinarySearch ls8 = new LinearNBinarySearch();
ls8.add(8, "eight");
ls8.add(1, "one");
ls8.add(2, "two");
ls8.add(3, "three");
String x;
x = (String) ls8.linearSearch(3);
hpPrinter(x);
x = (String) ls8.binarySearch(1);
hpPrinter(x);
x = (String) ls8.linearSearch(8);
hpPrinter(x);
x = (String) ls8.binarySearch(8);
hpPrinter(x);
}
private static void hpPrinter(String x) {
if (x != null) {
System.out.println("Searched data = " + x);
} else {
System.out.println("data Not found");
}
System.out.println("//-----------");
}
}
댓글 없음:
댓글 쓰기
국정원의 댓글 공작을 지탄합니다.