Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🔴 Advanced  ·  Lesson 63

Sorting and Searching in C++

Sorting और searching क्यों ज़रूरी हैं

Sorting (data को क्रम में लगाना) और searching (कोई item खोजना) data पर सबसे आम operations हैं — rank list, merit list, roll number खोजना, library में book है या नहीं देखना। C++ <algorithm> में इनके तेज़, tested versions देती है, और exams में classic algorithms हाथ से लिखने को भी कहा जाता है। यह lesson दोनों सिखाता है।

std::sort

C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

int main() {
    std::vector<int> marks = {66, 91, 78, 55, 84, 91};

    std::sort(marks.begin(), marks.end());                       // बढ़ता क्रम
    for (int m : marks) std::cout << m << " ";
    std::cout << "\n";

    std::sort(marks.begin(), marks.end(), std::greater<int>());  // घटता क्रम
    for (int m : marks) std::cout << m << " ";
    std::cout << "\n";

    int arr[] = {5, 2, 9, 1};
    std::sort(arr, arr + 4);                                     // साधारण arrays भी
    std::cout << arr[0] << " " << arr[3] << "\n";
    return 0;
}
55 66 78 84 91 91 91 91 84 78 66 55 1 9

std::sort O(n log n) में चलता है और इसे random-access iterators (vector, deque, arrays) चाहिए। std::list के लिए list.sort() लें।

Comparator से objects sort करना

C++
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

struct Student { std::string name; int marks; };

int main() {
    std::vector<Student> cls = {{"Ravi", 78}, {"Aman", 91}, {"Sara", 78}, {"Priya", 91}};

    // सबसे ज़्यादा marks पहले; बराबर हों तो नाम के alphabetical क्रम में
    std::sort(cls.begin(), cls.end(), [](const Student& a, const Student& b) {
        if (a.marks != b.marks) return a.marks > b.marks;
        return a.name < b.name;
    });

    int rank = 1;
    for (const auto& s : cls) std::cout << rank++ << ". " << s.name << " " << s.marks << "\n";
    return 0;
}
1. Aman 91 2. Priya 91 3. Ravi 78 4. Sara 78

Comparator तब true लौटाए जब a को b से पहले आना चाहिए, और वह strict ordering हो — बराबर elements के लिए कभी true न लौटाए (> की जगह >= से sort crash भी कर सकता है)।

Sorting के और functions

Functionकब इस्तेमाल करें
std::stable_sortबराबर elements का मूल क्रम बना रहे (जैसे marks से sort पर बराबरी में roll-number क्रम रहे)
std::partial_sort(b, b + k, e)सिर्फ ऊपर के k sorted चाहिए (top 3 rankers)
std::nth_elementk-th सबसे छोटा / median चाहिए, पूरा क्रम नहीं
std::is_sortedRange पहले से sorted है या नहीं
std::reverseRange उल्टी करना

find / find_if से linear search

किसी भी data पर चलता है, sorted हो या नहीं — O(n)।

C++
std::vector<int> rolls = {12, 7, 25, 3, 18};
auto it = std::find(rolls.begin(), rolls.end(), 25);
if (it != rolls.end())
    std::cout << "found at index " << (it - rolls.begin()) << "\n";   // 2

auto big = std::find_if(rolls.begin(), rolls.end(), [](int r) { return r > 15; });
std::cout << "first roll > 15: " << *big << "\n";                     // 25

Sorted data पर binary search

Binary search बीच के element को देखती है और हर कदम पर आधी range छोड़ देती है — O(log n)। Data उसी क्रम में sorted होना ज़रूरी है।

C++
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> marks = {35, 48, 55, 66, 66, 66, 78, 91};

    std::cout << std::boolalpha
              << "66 present? " << std::binary_search(marks.begin(), marks.end(), 66) << "\n"
              << "70 present? " << std::binary_search(marks.begin(), marks.end(), 70) << "\n";

    auto lo = std::lower_bound(marks.begin(), marks.end(), 66);   // पहला >= 66
    auto hi = std::upper_bound(marks.begin(), marks.end(), 66);   // पहला > 66
    std::cout << "66 appears " << (hi - lo) << " times, starting at index "
              << (lo - marks.begin()) << "\n";

    auto pos = std::lower_bound(marks.begin(), marks.end(), 70);
    std::cout << "70 would be inserted at index " << (pos - marks.begin()) << "\n";
    return 0;
}
66 present? true 70 present? false 66 appears 3 times, starting at index 3 70 would be inserted at index 6

Classic algorithms खुद लिखना

Bubble sort — O(n²)

C++
void bubbleSort(std::vector<int>& a) {
    for (size_t i = 0; i + 1 < a.size(); i++) {
        bool swapped = false;
        for (size_t j = 0; j + 1 < a.size() - i; j++) {
            if (a[j] > a[j + 1]) {
                std::swap(a[j], a[j + 1]);
                swapped = true;
            }
        }
        if (!swapped) break;          // पहले से sorted: जल्दी रुको
    }
}

Binary search — O(log n)

C++
int binarySearch(const std::vector<int>& a, int key) {
    int low = 0, high = static_cast<int>(a.size()) - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2;     // (low + high) के overflow से बचाव
        if (a[mid] == key) return mid;
        if (a[mid] < key)  low = mid + 1;
        else               high = mid - 1;
    }
    return -1;                                // नहीं मिला
}

और हाथ से लिखे sorts के लिए देखें bubble sort, selection और insertion sort और merge sort।

Complexity एक नज़र में

AlgorithmBestAverageWorstStable?
Bubble sortO(n)O(n²)O(n²)हाँ
Selection sortO(n²)O(n²)O(n²)नहीं
Insertion sortO(n)O(n²)O(n²)हाँ
Merge sort / stable_sortO(n log n)O(n log n)O(n log n)हाँ
std::sort (introsort)O(n log n)O(n log n)O(n log n)नहीं
Linear searchO(1)O(n)O(n)—
Binary searchO(1)O(log n)O(log n)—

आम गलतियाँ

  • Unsorted data पर binary_search या lower_bound चलाना — नतीजा बेमतलब।
  • Sort comparator में <= या >= — strict weak ordering टूटती है और crash हो सकता है।
  • std::sort(v.begin(), v.end() - 1) लिखकर आख़िरी element छोड़ देना।
  • बहुत बड़े indices पर mid = (low + high) / 2 — overflow हो सकता है; low + (high - low) / 2 लें।
  • list पर std::sort लगाना।
🏋️ अभ्यास

8 students के नाम और marks पढ़ें। Merit list print करें (marks घटते क्रम में, बराबरी पर नाम से)। फिर एक mark पूछें और marks की sorted copy पर lower_bound/upper_bound से बताएँ कि कितने students के ठीक उतने marks हैं और कितनों के ज़्यादा।

सारांश

  • std::sort O(n log n) में sort करता है; custom क्रम के लिए std::greater या lambda दें।
  • बराबरी में मूल क्रम रखना हो तो stable_sort; top-k के लिए partial_sort।
  • find/find_if = किसी भी data पर linear search।
  • binary_search, lower_bound, upper_bound = sorted data पर O(log n)।
  • Exams के लिए bubble sort और binary search हाथ से लिखना आना चाहिए।

संबंधित: STL algorithms, lambda, vector, C: binary search।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

C++ में vector को घटते क्रम में कैसे sort करें?
std::sort को comparator दें: std::sort(v.begin(), v.end(), std::greater<int>()); या lambda [](int a, int b) { return a > b; }। एक और तरीका std::sort(v.rbegin(), v.rend()); है, जो उल्टी range को बढ़ते क्रम में sort करता है।
std::sort कौन-सा sorting algorithm इस्तेमाल करता है?
Standard सिर्फ O(n log n) comparisons की माँग करता है। GCC, Clang और MSVC इसे introsort से बनाते हैं — quicksort जो recursion बहुत गहरी होने पर heapsort और छोटे हिस्सों के लिए insertion sort पर चला जाता है। यह stable नहीं है; बराबर elements का मूल क्रम बनाए रखना हो तो std::stable_sort लें।
Linear search और binary search में क्या अंतर है?
Linear search elements को एक-एक करके check करती है और किसी भी data पर O(n) time में चलती है। Binary search sorted range को बार-बार आधा करती है, O(log n) time लेती है, पर data पहले से sorted होना चाहिए। 10 लाख elements में linear search को दस लाख checks लग सकते हैं; binary search को लगभग 20।
lower_bound और upper_bound में क्या अंतर है?
Sorted range पर lower_bound(x) पहले ऐसे element का iterator लौटाता है जो x से छोटा नहीं है (≥ x), और upper_bound(x) x से बड़े पहले element का। दोनों के बीच की दूरी x के बराबर elements की संख्या होती है।
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 लाइव कोड एडिटर

इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.
अगला topicC++ Mini Projects आपकी प्रगति: 63 / 81 (78%) · Lesson 64 / 81 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें