Skip to content

added agnosticBinarySearch algorithm and Testcases for ascending and descending order #3882

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Feb 23, 2023
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.thealgorithms.searches;
import java.util.*;
public class sortOrderAgnosticBinarySearch {
public static int find(int arr[],int key){
int start = 0;
int end = arr.length-1;
boolean arrDescending = arr[start]>arr[end]; //checking for Array is in ascending order or descending order.
while(start<=end){
int mid = end-start/2;
if (arr[mid]==key){
return mid;
}
if(arrDescending){ // boolean is true then our array is in descending order
if(key<arr[mid]){
start=mid+1;
}
else{
end=mid-1;
}
}
else { // otherwise our array is in ascending order
if(key>arr[mid]){
start=mid+1;
}
else{
end=mid-1;
}
}
}
return -1;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.thealgorithms.searches;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;

public class sortOrderAgnosticBinarySearchTest{

@Test
public void testAscending(){
int arr[] = {1,2,3,4,5};// for ascending order.
int target = 2;
int ans=sortOrderAgnosticBinarySearch.find(arr, target);
int excepted = 1;
assertEquals(excepted,ans);
}

@Test
public void testDescending(){
int arr[] = {5,4,3,2,1};// for descending order.
int target = 2;
int ans=sortOrderAgnosticBinarySearch.find(arr, target);
int excepted = 3;
assertEquals(excepted,ans );
}

}