C/C++ Algorithms

Binary Search

हर comparison के बाद आधा range हट जाता है।

Binary Search क्या है?

हर comparison के बाद आधा range हट जाता है।

Sorted data logarithmic time में खोजें।

महत्वपूर्ण बातें

  • Empty, single, duplicate और sorted input test करें।
  • Correctness और optimization अलग रखें।
  • Production में standard library को प्राथमिकता दें।

Binary Search Visualizer

O(log n)

हर comparison और data movement देखने के लिए चलाएँ या अगला चरण दबाएँ।

C और C++ code examples

C
कोड चलाएँ →
main.c
#include <stdio.h>

int search(const int *values, int size, int target) {
    int low = 0;
    int high = size - 1;
    while (low <= high) {
        int middle = low + (high - low) / 2;
        if (values[middle] == target) return middle;
        if (values[middle] < target) low = middle + 1;
        else high = middle - 1;
    }
    return -1;
}

int main(void) {
    int values[] = {3, 7, 11, 16, 23, 28};
    printf("index=%d\n", search(values, 6, 23));
}
अपेक्षित output
index=4
C++
कोड चलाएँ →
main.cpp
#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector values{3, 7, 11, 16, 23, 28};
    auto match = std::lower_bound(values.begin(), values.end(), 23);
    std::cout << "index="
              << std::distance(values.begin(), match) << '\n';
}
अपेक्षित output
index=4

C और C++ की तुलना

Input sorted होना चाहिए। C loop और std::lower_bound random-access range पर O(log n) हैं।

C

Loops, pointers, lengths और buffers स्पष्ट लिखे जाते हैं।

C++

Iterators और algorithms operation को storage से अलग करते हैं।

अभ्यास

दोनों versions चलाकर बदलें और language guarantees की तुलना करें।

  • हर comparison trace करें।
  • Duplicates और extreme values test करें।
  • Standard library के विरुद्ध benchmark करें।