오우~ 최악인데...
package algorithm.search;
import java.util.Random;
import algorithm.sort.quick.*;
public class BinarySearch {
public static void main(String[] arguments) throws InterruptedException {
int[] array = new int[300];
Random random = new Random();
for (int index = 0; index < array.length; index++) {
array[index] = random.nextInt(array.length);
}
for (int temp : array) {
System.out.print(temp + " ");
}
System.out.println();
QuickSort quick = new QuickSort(array);
array = quick.getSort();
for (int temp : array) {
System.out.print(temp + " ");
}
System.out.println();
int search = 289; //
int result = -1;
int right = array.length;
int left = 0;
int pivot = array.length / 2;
int temp = -1;
int count = 0;
while (true) {
count++;
if (array[pivot] == search) {
result = pivot;
break;
} else if (array[pivot] > search) {
right = pivot;
pivot = pivot - ((pivot - left) / 2);
if (temp == pivot) {
break;
}
temp = pivot;
} else {
left = pivot;
pivot = pivot + ((right - pivot) / 2);
if (temp == pivot) {
break;
}
temp = pivot;
}
}
if (result == -1) {
System.out.println("찾고자하는 결과값이 없습니다. 검색 횟수: " + count);
} else {
System.out.println("index " + result + "에 있습니다. " + array[result] + "검색횟수: " + count);
}
}
}
'ALGORITHM' 카테고리의 다른 글
TRANSPOSE METHOD (0) | 2011.04.18 |
---|---|
VERSION UP! 0.1 (0) | 2011.04.18 |
MOVE TO FRONT METHOD (0) | 2011.04.18 |
SEARCH ABSTRACT CLASS & NODE CLASS (0) | 2011.04.18 |
QUICK SORT (0) | 2011.04.16 |