Monday, May 16, 2016

Binary Search Example in Java

Here is a binary search code in Java programming language:

package com.kpatil.search;

public class BinarySearch {
 /**
  * Returns true if the given element is found in the list supplied.
  * 
  * @param list of integers
  * @param element to search
  * @return true if a given element is found in the list
  * 
  */
 public static boolean binarySearch(int[] list, int k) {

  if (list == null || list.length == 0) {
   return false;
  }

  int low = 0;
  int high = list.length - 1;

  while (low <= high) {
   // int mid = (high + low) / 2;
   int mid = low + ((high - low) / 2);
   if (list[mid] == k) {
    return true;
   } else if (list[mid] > k) {
    high = mid - 1;
   } else {
    low = mid + 1;
   }
  }

  return false;
 }

}

JUnit test cases:

package com.kpatil.test;

import static org.junit.Assert.*;

import org.junit.Test;

import com.kpatil.search.BinarySearch;

public class BinarySearchTest {

 @Test
 public void test1() {
  int[] list = { 3, 5, 7, 9, 11, 54, 59, 123 };
  assertEquals(true, BinarySearch.binarySearch(list, 123));
 }

 @Test
 public void test2() {
  int[] list = { 3, 5, 7, 9, 11, 54, 59, 123 };
  assertEquals(false, BinarySearch.binarySearch(list, 152));
 }

 @Test
 public void test3() {
  int[] list = null;
  assertEquals(false, BinarySearch.binarySearch(list, 2));
 }

 @Test
 public void test4() {
  int[] list = {2};
  assertEquals(true, BinarySearch.binarySearch(list, 2));
 }
 
 @Test
 public void test5() {
  int[] list = {};
  assertEquals(false, BinarySearch.binarySearch(list, 25));
 }

}

No comments:

Post a Comment