package org.wesome.dsalgo;
public class BinarySearch {
public static int binarySearch(int[] arr, int start, int end, int find) {
if (start > end) {
return -1;
}
int mid = start + (end - start) / 2;
if (arr[mid] == find) {
return mid;
}
// If the element is present at the middle itself
if (arr[mid] >= find) {
// If element is smaller than mid, then it can only be present in left subarray
return binarySearch(arr, start, mid - 1, find);
}
// Else the element can only be present in right subarray
else return binarySearch(arr, mid + 1, end, find);
}
}
package org.wesome.dsalgo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.wesome.dsalgo.BinarySearch.binarySearch;
class BinarySearchTest {
@Test
void binarySearchTest1() {
int[] arr = new int[]{1, 2, 3, 4, 5};
int binarySearch = binarySearch(arr, 0, arr.length, 4);
Assertions.assertEquals(3, binarySearch);
}
@Test
void binarySearchTest2() {
int[] arr = new int[]{1, 2, 3, 4, 5};
int binarySearch = binarySearch(arr, 0, arr.length, 1);
Assertions.assertEquals(0, binarySearch);
}
@Test
void binarySearchTest3() {
int[] arr = new int[]{1, 2, 3, 4, 5};
int binarySearch = binarySearch(arr, 0, arr.length, 5);
Assertions.assertEquals(4, binarySearch);
}
}
plugins {
id 'java'
}
group 'org.wesome'
version '1.0-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8
repositories {
mavenCentral()
}
dependencies {
testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
}
test {
useJUnitPlatform()
}