Binary Search

Java 2012.01.26 14:19 |

샘플 코드 >

public class BinarySearch {
	public static boolean contains(int[] a, int b) {
		if (a.length == 0) {
			return false;
		}
		int low = 0;
		int high = a.length-1;

		while(low <= high ) {
			int middle = (low+high) /2; 
			if (b> a[middle] ){
				low = middle +1;
			} else if (b< a[middle]){
				high = middle -1;
			} else { // The element has been found
				return true; 
			}
		}
		return false;
	}
}


jUnit 테스트 >

import org.junit.Test;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class BinarySearchTest {

	@Test
	public void testContains() {
		int[]a = {1, 2, 3, 4, 5, 7, 17,  19 };
//		assertTrue(BinarySearch.contains(a, 17));
		assertTrue(BinarySearch.contains(a, 1));
		assertTrue(BinarySearch.contains(a, 2));
		assertTrue(BinarySearch.contains(a, 3));
		assertTrue(BinarySearch.contains(a, 4));
		assertFalse(BinarySearch.contains(a, 10));
	}

}





 
신고

'Java' 카테고리의 다른 글

Java 1.7 New Features 코드 샘플  (0) 2012.02.09
정렬 알고리즘  (0) 2012.02.04
Binary Search  (3) 2012.01.26
Sequential Search  (0) 2012.01.26
java에서 손쉽게 JSON을 사용한다. JSON.simple example – Read and write JSON  (0) 2012.01.20
Java Garbage Collection  (0) 2012.01.19
Posted by jeonguk