C/C++ Algorithms

Linear Search

Linear search match या अंत तक हर element जाँचता है।

Linear Search क्या है?

Linear search match या अंत तक हर element जाँचता है।

Unsorted data में target खोजें।

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

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

Linear Search Visualizer

O(n)

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

C और C++ code examples

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

int find(const int *values, int size, int target) {
    for (int index = 0; index < size; ++index) {
        if (values[index] == target) return index;
    }
    return -1;
}

int main(void) {
    int values[] = {14, 3, 27, 8, 19};
    printf("index=%d\n", find(values, 5, 8));
}
अपेक्षित output
index=3
C++
कोड चलाएँ →
main.cpp
#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector values{14, 3, 27, 8, 19};
    auto match = std::find(values.begin(), values.end(), 8);
    std::cout << "index="
              << std::distance(values.begin(), match) << '\n';
}
अपेक्षित output
index=3

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

Worst case O(n) है। C missing पर -1 और C++ end से compare होने वाला iterator लौटाता है।

C

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

C++

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

अभ्यास

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

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