Contents Menu Expand Light mode Dark mode Auto light/dark, in light mode Auto light/dark, in dark mode Skip to content
Logo

Contents:

  • Conventions
  • Overview
  • Software
    • Software Manual
  • User Manual
    • Introduction to User Manual
  • Python Programs
  • C++ Programs
    • C++ Intro
  • Bibliography
  • Lex Land
  • Journal
    • Binary Search
    • Dynamic Data Structures
    • Stacks and Queues
    • Binary Search Trees
    • Tries and Adapting Data Structures
  • Programming Language
    • Prolog with Visual Studio Code
    • Chapters One and Two Python Program/Notes
    • Chapters Three and Four Python Program/Notes
    • Chapters Five and Six Python Program/Notes
    • Chapter Seven Python Program/Notes
    • Chapter Eight Python Program/Notes
    • Chapter Nine Python Program/Notes
    • Chapter Ten Python Program/Notes
    • Chapter Eleven Python Program/Notes
  • Networking
    • Unit 1: Networking Fundamentals with EduNetworkBuilder
    • Unit 2: Packet Analysis
    • Unit 3: SIEM Tools & Event Analysis
    • Unit 4: System Hardening — Reducing Attack Surfaces
    • UNIT 5: NETWORK SECURITY ASSESSMENT
    • 5.1 Introduction to Network Security Assessment
    • 5.2 Types of Security Assessments
    • 5.3 Legal and Ethical Foundations
    • 5.4 Assessment Methodology and Phases
    • 5.5 Common Network Vulnerabilities
    • 5.6 Assessment Tools Reference
    • 5.7 Defensive Countermeasures
    • 5.8 Reporting and Remediation Follow-Up
    • 5.9 Chapter Summary
    • 5.10 Key Terms
    • 5.11 Further Reading and References
  • Opperating Systems
    • Syllabus Project
Back to top
View this page

Binary Search¶

Here’s something!

#include <iostream>
#include <vector>
using namespace std;

int binarySearch(vector<int> &arr, int x) {
    // Giving a starting point and an ending point
    int low = 0;
    int high = arr.size() - 1;
    //Do all of this, so long as we dont find anything or end
    while (low <= high) {
        int mid = low + (high - low) / 2;

        // See if x is present at mid
        if (arr[mid] == x)
            return mid;

        // If x greater, ignore left half
        if (arr[mid] < x)
            low = mid + 1;

        // If x is smaller, ignore right half
        else
            high = mid - 1;
    }

    // If we reach here, then element was not present
    return -1;
}

int main() {
    vector<int> arr = { 2, 3, 4, 10, 40 };
    int x = 10;
    int result = binarySearch(arr, x);
    if(result == -1) cout << "Element is not present in array";
    else cout << "Element is present at index " << result << "\n";
    return 0;
}

The whole point of a binary search is to search through data that’s already been sorted through. If it’s not already sorted, then there’s really no point to it.

Next
Dynamic Data Structures
Previous
Journal
Copyright © 2025, ajp
Made with Sphinx and @pradyunsg's Furo