Pages

Tuesday, May 27, 2025

Binary Search in C++ (University Topic)

#include <iostream>
using namespace std;

int binarySearch(int arr[], int size, int element) {

    int low, mid, high;
    low = 0;
    high = size-1;  // high last element thats why


    // Start searching
    while(low<=high) {

        mid = (low+high)/2;
        if(arr[mid]==element) {

            return mid;

    }
        if(arr[mid]<element) {
            low = mid+1;

        }
        else {
            high = mid-1;

        }
    }
    // Searching end

    return -1;

}


int main() {
    // Unsorted array for linear search
    // int arr[] = {1,2,3,4,5,5,6,432,432,4,2342,34};
    // int size = sizeof(arr)/sizeof(int);
    // Sorted array for binary search
    int arr[] = {1,3,5,56,64,73,123,225,444};
    int size = sizeof(arr)/sizeof(int);
    int element = 56;
    int searchIndex = binarySearch(arr, size, element);
    cout << "The element " << element << " was found at index " << searchIndex << endl;

    return 0;
}

No comments:

Post a Comment

3917. Count Indices With Opposite Parity (Brute Force) O(n2) + Optimized Solution O(n) + tips LEETCODE WEEKLY 500

  class Solution {     public int [] countOppositeParity ( int [] nums ) {          // approach 1 - checks every pair         int n = n...