From 6b9eb1b9c1eddd1615a1d00d99d3e1c7f77fdbac Mon Sep 17 00:00:00 2001 From: HumbleFool <111487330+HumbleFool830@users.noreply.github.com> Date: Thu, 23 Feb 2023 22:49:05 +0530 Subject: [PATCH] Add orderAgnosticBinarySearch (#3882) Co-authored-by: Andrii Siriak --- .../sortOrderAgnosticBinarySearch.java | 32 +++++++++++++++++++ .../sortOrderAgnosticBinarySearchTest.java | 27 ++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java create mode 100644 src/test/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearchTest.java diff --git a/src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java b/src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java new file mode 100644 index 00000000..9f60b31b --- /dev/null +++ b/src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java @@ -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(keyarr[mid]){ + start=mid+1; + } + else{ + end=mid-1; + } + } + } + return -1; + } +} diff --git a/src/test/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearchTest.java b/src/test/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearchTest.java new file mode 100644 index 00000000..37f1aa40 --- /dev/null +++ b/src/test/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearchTest.java @@ -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 ); + } + +} \ No newline at end of file