Home > OS >  More efficient way to do binary search in c ?
More efficient way to do binary search in c ?

Time:12-10

I am doing a question on Binary Search using C , but I was wondering if there is a more efficient way to implement it.

My code is as follows:

int binarySearch(int arr[], int l, int r, int x) {
    if (r >= l) {
        int mid = l   (r - l) / 2;
 
        if (arr[mid] == x) {
            return mid;
        } else if (arr[mid] > x) {
            return binarySearch(arr, l, mid - 1, x);
        } else {
            return binarySearch(arr, mid   1, r, x);
        }
    } else {
        return -1;
    }
}

CodePudding user response:

Binary Search is a very efficient method for searching any particular value in our arrays.. especially in very long-sized arrays, where the conventional linear search method can consume huge compilation time. Talking about time complexities => linear search O(n) whereas Binary Search have time complexity: O(log2n) {log n with base 2}

so there are no other optimizations needed in is this binary search code but yeah.. instead of binary search you can learn about TERNARY SEARCH which is even more faster than Binary Search https://www.geeksforgeeks.org/ternary-search/

Ternary Search is just like Binary Search, but in this, the array is divided into 3 parts then we do the comparison. Also the time complexity of Ternary Searcg is O(log3n) :log n with base 3

  • Related