Skip to main content

An attempt to Implement Binary Search STL (associative) Containers agnostic way.

 Binary Search is a very trivial algorithm to search a target value from a sorted array. It's popular among students of computer science and also during interviews it gets asked by the interviewer. It's easy. We take an array of integers already sorted and apply binary search on that array to figure out if the target value does present in that sorted array or not. 

The condition can be either present or not present. If it is present we return the array index of the element else we return -1.

The algorithm is very simple, it's broken down into three parts.

1. Find and compare the middle element of the search space with the key.

2. If the key is found in the middle, just return the array index.

3. If the key is not found then choose half of the array space, based on whether the key value is smaller or greater than the mid element. 

    a. If the key element is smaller than the mid element, then the left side of the search space will be used otherwise, the right side of the search space will be used. 

This process continues until the element is found in the search space or the total search space is exhausted. 

The very standard implementation is more or less like the below in C++:

int BinarySearch(const std::vector<int>& vec, const int&& target)
{
    if (vec.size() == 0) return -1;
    int left = 0;
    int right = static_cast<int>(vec.size() - 1);

    while (left <= right)
    {
        int mid = left + ((right - left) >> 2);
        if (vec[mid] == target) return mid;
        if (vec[mid] < target) left = mid + 1;
        else right = mid - 1;
    }
    return -1;
}

int main()
{
    std::vector<int> v = 
    { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 
       17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 
       31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 
       45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 
       59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 
       73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 
       87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100 };

    std::cout << "Non templated Imp(std::vector used): " << BinarySearch(v, 2) << "\n";
    std::cout << "Non templated Imp(std::vector used): " << BinarySearch(v, 99) << "\n";
    std::cout << "Non templated Imp(std::vector used): " << BinarySearch(v, 300) << "\n";

    return 0;
}

And it works. But now comes the twist, what if we want a binary search implementation that should work for most of the STLs associative containers like vector, list, array, and deque. In summary, want an implementation for STLs associative containers like vector, array, list, and deque. The idea is to develop the binary search in such a way that it can work container agnostic way. Hence followed templated approach and instead of passing the container itself used Iterator. It's a templatized Iterator-based approach. The below implementation works for std::vector, std::list, std::array, std::deque, and std::set. I've used visual studio 2022 for my implementation and the code looks like the below:

template<typename T, typename It>
_int64 BinarySearchT(It begin, It end, const T&& target)
{
    if (begin == end) 
        return -1;

    It left = begin;
    It right = std::prev(end);

    // Check for a container with one element
    if (left == right)
    {
        if (*left == target) return 0;
        else return -1;
    }

    while (left != end)
    {
        auto mid = left;
        std::advance(mid, std::distance(left, right) >> 2);
        if (*mid == target) return std::distance(begin, mid);
        else if (*mid < target) {
            left = mid;
            std::advance(left, 1);
        }
        else 
        {
            right = mid;
            end = right;
            std::advance(right, -1);
        }
    }

    return -1;
}

As we can see I have used Iterators to search the key element in search space(containers) which could be a std::array or std::vector or std::list or std::deque or std::set. 

Here is the complete demo code:

*For GCC compiler function return shall be int64_t instead of _int64. 
** The implementation doesn't work for std::forward_list.

Comments

Popular posts from this blog

XOR (Exclusive OR) for branchless coding

The following example shows the array reversing using the  XOR operator . No need to take any additional variable to reverse the array.   int main(int argc, _TCHAR* argv[]) { char str[] = "I AM STUDENT"; int length = strlen(str); for(int i = 0; i < ((length/2)); i++) { str[i] ^= str[length - (1+i)]; str[length - (1+i)] ^= str[i]; str[i] ^= str[length - (1+i)]; } cout << str << endl; return 0; } The above example is one of the uses of XOR but XOR comes in handy when we can do branchless coding  methods like butterfly switch etc. Sometimes this is very effective in speeding up the execution.  Let's see one of the uses of XOR in branchless coding. I am taking a simple example of Y = | X |.  Yes, I am generating abs of a supplied number. So, my function signature/definition in C++ looks like below: int absoluteBranch( int x) {     if (x < 0 ) {         return ...

Reversing char array without splitting the array to tokens

 I was reading about strdup, a C++ function and suddenly an idea came to my mind if this can be leveraged to aid in reversing a character array without splitting the array into words and reconstructing it again by placing spaces and removing trailing spaces. Again, I wanted an array to be passed as a function argument and an array size to be passed implicitly with the array to the function. Assumed, a well-formed char array has been passed into the function. No malformed array checking is done inside the function. So, the function signature and definition are like below: Below is the call from the client code to reverse the array without splitting tokens and reconstructing it. Finally, copy the reversed array to the destination.  For GNU C++, we should use strdup instead _strdup . On run, we get the following output: Demo code

Power of Two

  I n this post will be discussing how to calculate if a number is a power of two or not. As an example, 8 is a power of two but the number 10 is not. There are many ways we can solve this. First , we will take an approach which is simple and iterative. In this case, we will calculate the power of two one by one and check with the supplied number. The below code illustrates it. bool isPowerofTwo(unsigned num) { auto y = 1; while (0 != y) { if (num == y) return true; if (num < y) return false; y <<= 1; } return false; } Second , assuming, the number is a 32-bit number, this is also an iterative solution. In this scenario, iterating all bits and counting the set bits. Any number which is a power of 2 will have only one bit set and the rest will be zeros. As an example, 8 in binary representation is 1000. Using this observation, we can implement an iterative solution. bool isPowerofTwo(unsigned num) { auto one_count = 0; for (auto index = 0; index < ...