category-wise-problems

contains category wise problems(data structures, competitive) of popular platforms.

View the Project on GitHub mayankdutta/category-wise-problems

Binary Search

Method 1

int search(vector<int>& nums, int target) {
    int low = -1;
    int high = nums.size();

    while (low  + 1 < high) {
        int mid = (low + high) / 2;

        if (nums[mid] == target) {
            return mid;
        }
        else if (target < nums[mid]) {
            high = mid;
        }
        else {
            low = mid;
        }
    }
    return -1;
}

Method 2

int search(vector<int>& nums, int target) {
    int low = 0;
    int high = nums.size() - 1;

    for (int t = 0; t < 50; t++) {
        int mid = (low + high) / 2;

        if (nums[mid] == target) {
            return mid;
        }
        else if (target < nums[mid]) {
            high = mid - 1;
        }
        else {
            low = mid + 1;
        }
    }
    return -1;
}

Method 3

int search(vector<int>& nums, int target) {
   int low = 0;
   int high = nums.size() - 1;

   while (low <= high) {
       int mid = (low + high) / 2;

       if (nums[mid] == target) {
           return mid;
       }
       else if (target < nums[mid]) {
           high = mid - 1;
       }
       else {
           low = mid + 1;
       }
   }
   return -1;
}