ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCC-213Binary Search Sorted A…
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CC-213

    Data Structures & Algorithms

    Progress0 / 37 done
    Topics37
    1Abstract Data Types2Complexity Analysis3Big Oh Notation4Stacks (Linked Lists and Array Implementations)5Recursion and analyzing recursive algorithms6Divide and Conquer Algorithms7Sorting Algorithms8Selection Sort9Insertion Sort10Merge Sort11Quick Sort12Bubble Sort13Heap Sort14Shell Sort15Radix Sort16Bucket Sort17Queue18Dequeuer19Priority Queues (linked and array implementations of queues)20Linked List and Its Various Types21Sorted Linked List22Searching an Unsorted Array23Binary Search for Sorted Arrays24Hashing and Indexing25Open Addressing and Chaining26Trees and Tree Traversals27Binary Search Trees28Heaps29M-Way Trees30Balanced Trees31Graphs32Breadth-First Traversal33Depth-First Traversal34Topological Order35Shortest Path36Adjacency Matrix and Adjacency List Implementations37Memory Management and Garbage Collection
    5 min read
    Topic 23 of 37
    Topic Study Note Illustration
    23

    Binary Search for Sorted Arrays

    Binary search is a highly efficient algorithm for finding an element's position in a sorted array. Unlike linear search, which checks each element sequentially, binary search works...

    Binary Search for Sorted Arrays

    Binary search is a highly efficient algorithm for finding an element's position in a sorted array. Unlike linear search, which checks each element sequentially, binary search works by repeatedly dividing the search interval in half. This requires the array to be sorted beforehand.

    Key Characteristics

    1. Precondition: The array must be sorted in ascending (or descending) order.
    2. Time Complexity: The worst-case time complexity is O(log⁡n)O(\log n)O(logn), where nnn is the number of elements in the array.
    3. Space Complexity: The space complexity is O(1)O(1)O(1) for the iterative version and O(log⁡n)O(\log n)O(logn) for the recursive version due to call stack usage.

    How Binary Search Works

    1. Initialization: Start with two pointers, low and high, which represent the bounds of the search area. Initially, low is set to the first index (0), and high is set to the last index (n - 1).
    2. Calculate Midpoint: Compute the midpoint index: mid = (low + high) / 2.
    3. Comparison:
      • If the target value equals the element at the midpoint, the search is successful.
      • If the target value is less than the element at the midpoint, narrow the search to the left half by updating high.
      • If the target value is greater than the element at the midpoint, narrow the search to the right half by updating low.
    4. Repeat: Continue the process until the target is found or the search interval is empty (low > high).

    Example Code

    Here’s a simple C++ implementation of binary search for a sorted array:

    #include <iostream>
    using namespace std;
    
    // Function to perform binary search
    int binarySearch(int arr[], int size, int target) {
        int low = 0;
        int high = size - 1;
    
        while (low <= high) {
            int mid = low + (high - low) / 2; // Avoids potential overflow
    
            if (arr[mid] == target) {
                return mid; // Return the index if found
            } else if (arr[mid] < target) {
                low = mid + 1; // Search in the right half
            } else {
                high = mid - 1; // Search in the left half
            }
        }
        return -1; // Return -1 if the target is not found
    }
    
    int main() {
        int arr[] = {1, 3, 5, 7, 9, 11}; // Example sorted array
        int size = sizeof(arr) / sizeof(arr[0]);
        int target = 7;
    
        int result = binarySearch(arr, size, target);
        if (result != -1) {
            cout << "Element found at index: " << result << endl; // Output: Element found at index: 3
        } else {
            cout << "Element not found." << endl; // Output if not found
        }
    
        return 0;
    }
    

    Explanation of the Code

    1. Function Definition: The binarySearch function takes a sorted array, its size, and the target value as parameters.
    2. Initialization: low is set to 0 and high to the last index of the array.
    3. Loop: The while loop continues as long as low is less than or equal to high.
    4. Midpoint Calculation: The midpoint index is calculated. Using low + (high - low) / 2 helps avoid potential overflow.
    5. Comparison:
      • If the target is found at mid, its index is returned.
      • If the target is less than the midpoint value, the search continues in the left half by updating high.
      • If the target is greater, the search continues in the right half by updating low.
    6. Return Value: If the target is not found, the function returns -1.
    7. Main Function: Initializes a sorted array, specifies a target value, calls binarySearch, and prints the result.

    Complexity Analysis

    • Time Complexity:
      • The algorithm operates in O(log⁡n)O(\log n)O(logn) time, making it very efficient for large datasets.
    • Space Complexity:
      • The iterative version uses O(1)O(1)O(1) space. The recursive version uses O(log⁡n)O(\log n)O(logn) space due to recursion stack.

    Conclusion

    Binary search is a powerful and efficient algorithm for searching in sorted arrays. Its logarithmic time complexity allows it to handle large datasets efficiently, making it a fundamental technique in computer science and programming. Always ensure that the array is sorted before applying binary search, as it relies on the order of elements for its functionality.

    ← Previous topic 22
    Searching an Unsorted Array
    Next topic 24 →
    Hashing and Indexing

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    5mremaining
    786words
    Beginnerlevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Data Structures & Algorithms