Skip to content

Commit 6b9eb1b

Browse files
SunilKumar-Ksiriak
andauthored
Add orderAgnosticBinarySearch (TheAlgorithms#3882)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
1 parent 3c0d942 commit 6b9eb1b

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.thealgorithms.searches;
2+
import java.util.*;
3+
public class sortOrderAgnosticBinarySearch {
4+
public static int find(int arr[],int key){
5+
int start = 0;
6+
int end = arr.length-1;
7+
boolean arrDescending = arr[start]>arr[end]; //checking for Array is in ascending order or descending order.
8+
while(start<=end){
9+
int mid = end-start/2;
10+
if (arr[mid]==key){
11+
return mid;
12+
}
13+
if(arrDescending){ // boolean is true then our array is in descending order
14+
if(key<arr[mid]){
15+
start=mid+1;
16+
}
17+
else{
18+
end=mid-1;
19+
}
20+
}
21+
else { // otherwise our array is in ascending order
22+
if(key>arr[mid]){
23+
start=mid+1;
24+
}
25+
else{
26+
end=mid-1;
27+
}
28+
}
29+
}
30+
return -1;
31+
}
32+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.thealgorithms.searches;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
public class sortOrderAgnosticBinarySearchTest{
8+
9+
@Test
10+
public void testAscending(){
11+
int arr[] = {1,2,3,4,5};// for ascending order.
12+
int target = 2;
13+
int ans=sortOrderAgnosticBinarySearch.find(arr, target);
14+
int excepted = 1;
15+
assertEquals(excepted,ans);
16+
}
17+
18+
@Test
19+
public void testDescending(){
20+
int arr[] = {5,4,3,2,1};// for descending order.
21+
int target = 2;
22+
int ans=sortOrderAgnosticBinarySearch.find(arr, target);
23+
int excepted = 3;
24+
assertEquals(excepted,ans );
25+
}
26+
27+
}

0 commit comments

Comments
 (0)