ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Data Structures
    COMP2117
    Progress0 / 37 topics
    Topics
    1. Abstract Data Types2. Complexity Analysis3. Big Oh Notation4. Stacks (Linked Lists and Array Implementations)5. Recursion and analyzing recursive algorithms6. Divide and Conquer Algorithms7. Sorting Algorithms8. Selection Sort9. Insertion Sort10. Merge Sort11. Quick Sort12. Bubble Sort13. Heap Sort14. Shell Sort15. Radix Sort16. Bucket Sort17. Queue18. Dequeuer19. Priority Queues (linked and array implementations of queues)20. Linked List and Its Various Types21. Sorted Linked List22. Searching an Unsorted Array23. Binary Search for Sorted Arrays24. Hashing and Indexing25. Open Addressing and Chaining26. Trees and Tree Traversals27. Binary Search Trees28. Heaps29. M-Way Trees30. Balanced Trees31. Graphs32. Breadth-First Traversal33. Depth-First Traversal34. Topological Order35. Shortest Path36. Adjacency Matrix and Adjacency List Implementations37. Memory Management and Garbage Collection
    COMP2117›Binary Search for Sorted Arrays
    Data StructuresTopic 23 of 37

    Binary Search for Sorted Arrays

    5 minread
    786words
    Beginnerlevel

    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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time5 min
      Word count786
      Code examples0
      DifficultyBeginner