← Back to DSA Course | Chapter 1: Introduction & Complexity | Lesson 4 of 6

Best, Worst और Average Case

एक algorithm lucky या unlucky हो सकता है: पहले box में अपना toy ढूंढना best case है, आखिरी box में worst case है, और average बीच में कहीं है।

Case Analysis

वही algorithm बहुत अलग समय ले सकता है इस आधार पर कि इसे कौन सा specific input मिलता है, सिर्फ input के size के आधार पर नहीं। किसी algorithm को properly analyze करने का मतलब है हर run पर performance वही मानने के बजाय एक से ज़्यादा scenario देखना।

उदाहरण: Case Analysis

#include <iostream>
using namespace std;
int linearSearch(int arr[], int n, int target) {
    for (int i = 0; i < n; i++)
        if (arr[i] == target) return i;
    return -1;
}
int main() {
    int arr[] = {5, 3, 8, 1, 9};
    cout << "Best case (found at 0): " << linearSearch(arr, 5, 5) << endl;
    cout << "Worst case (not found): " << linearSearch(arr, 5, 100) << endl;
    return 0;
}
public class Main {
    static int linearSearch(int[] arr, int target) {
        for (int i = 0; i < arr.length; i++)
            if (arr[i] == target) return i;
        return -1;
    }
    public static void main(String[] args) {
        int[] arr = {5, 3, 8, 1, 9};
        System.out.println("Best case (found at 0): " + linearSearch(arr, 5));
        System.out.println("Worst case (not found): " + linearSearch(arr, 100));
    }
}
def linear_search(arr, target):
    for i, x in enumerate(arr):
        if x == target:
            return i
    return -1

arr = [5, 3, 8, 1, 9]
print("Best case (found at 0):", linear_search(arr, 5))
print("Worst case (not found):", linear_search(arr, 100))
#include <stdio.h>
int linearSearch(int arr[], int n, int target) {
    for (int i = 0; i < n; i++)
        if (arr[i] == target) return i;
    return -1;
}
int main() {
    int arr[] = {5, 3, 8, 1, 9};
    printf("Best case (found at 0): %d\n", linearSearch(arr, 5, 5));
    printf("Worst case (not found): %d\n", linearSearch(arr, 5, 100));
    return 0;
}

Average Case

Average case inputs के एक realistic mix में expected running time describe करता है, जो अक्सर practice में absolute best या worst case से ज़्यादा उपयोगी है, लेकिन इसे calculate करना भी ज़्यादा मुश्किल है क्योंकि इसे आमतौर पर input distribution के बारे में assumptions चाहिए।

उदाहरण: Average Case

#include <iostream>
using namespace std;
int main() {
    int arr[] = {2, 4, 6, 8, 10};
    int n = 5;
    long totalPositionsChecked = 0;
    for (int target = 0; target < n; target++) {
        for (int i = 0; i <= target; i++) totalPositionsChecked++;
    }
    cout << "Average checks per search: " << (double)totalPositionsChecked / n << endl;
    return 0;
}
public class Main {
    public static void main(String[] args) {
        int n = 5;
        long totalPositionsChecked = 0;
        for (int target = 0; target < n; target++)
            for (int i = 0; i <= target; i++) totalPositionsChecked++;
        System.out.println("Average checks per search: " + ((double) totalPositionsChecked / n));
    }
}
n = 5
total_positions_checked = sum(i + 1 for target in range(n) for i in range(target + 1))
print("Average checks per search:", total_positions_checked / n)
#include <stdio.h>
int main() {
    int n = 5;
    long totalPositionsChecked = 0;
    for (int target = 0; target < n; target++)
        for (int i = 0; i <= target; i++) totalPositionsChecked++;
    printf("Average checks per search: %.1f\n", (double)totalPositionsChecked / n);
    return 0;
}

Search Example

Linear search एक साफ़ example है: best case में target बिल्कुल पहला element है (O(1)), worst case में यह आखिरी element है या बिल्कुल गायब (O(n)), और average में, एक random position मानते हुए, यह लगभग आधे elements जांचता है।

उदाहरण: Search Example

#include <iostream>
using namespace std;
int main() {
    int arr[] = {7, 2, 9, 4, 1};
    // Best case: target is arr[0] -> 1 comparison.
    // Worst case: target is arr[4] or missing -> 5 comparisons.
    cout << "arr[0]=" << arr[0] << " best-case target" << endl;
    cout << "arr[4]=" << arr[4] << " worst-case target" << endl;
    return 0;
}
public class Main {
    public static void main(String[] args) {
        int[] arr = {7, 2, 9, 4, 1};
        // Best case: target is arr[0] -> 1 comparison.
        // Worst case: target is arr[4] or missing -> 5 comparisons.
        System.out.println("arr[0]=" + arr[0] + " best-case target");
        System.out.println("arr[4]=" + arr[4] + " worst-case target");
    }
}
arr = [7, 2, 9, 4, 1]
# Best case: target is arr[0] -> 1 comparison.
# Worst case: target is arr[4] or missing -> 5 comparisons.
print("arr[0]=", arr[0], "best-case target")
print("arr[4]=", arr[4], "worst-case target")
#include <stdio.h>
int main() {
    int arr[] = {7, 2, 9, 4, 1};
    /* Best case: arr[0], 1 comparison. Worst case: arr[4] or missing, 5 comparisons. */
    printf("arr[0]=%d best-case target\n", arr[0]);
    printf("arr[4]=%d worst-case target\n", arr[4]);
    return 0;
}

Sorting Example

Sorting algorithms case analysis के लिए विशेष रूप से sensitive हैं। Quicksort average में O(n log n) में चलता है लेकिन already-sorted या adversarial input पर worst case में O(n²) तक degrade होता है, यही बिल्कुल कारण है कि एक अच्छी pivot strategy मायने रखती है।

उदाहरण: Sorting Example

#include <iostream>
using namespace std;
int main() {
    int sortedArr[] = {1, 2, 3, 4, 5};
    // Quicksort on already-sorted input with a bad pivot choice
    // degrades from average O(n log n) to worst-case O(n^2).
    cout << "sortedArr[0]=" << sortedArr[0] << " (adversarial input for quicksort)" << endl;
    return 0;
}
public class Main {
    public static void main(String[] args) {
        int[] sortedArr = {1, 2, 3, 4, 5};
        // Quicksort on already-sorted input with a bad pivot choice
        // degrades from average O(n log n) to worst-case O(n^2).
        System.out.println("sortedArr[0]=" + sortedArr[0] + " (adversarial input for quicksort)");
    }
}
sorted_arr = [1, 2, 3, 4, 5]
# Quicksort on already-sorted input with a bad pivot choice
# degrades from average O(n log n) to worst-case O(n^2).
print("sorted_arr[0]=", sorted_arr[0], "(adversarial input for quicksort)")
#include <stdio.h>
int main() {
    int sortedArr[] = {1, 2, 3, 4, 5};
    /* Quicksort on sorted input with a bad pivot degrades to O(n^2). */
    printf("sortedArr[0]=%d (adversarial input for quicksort)\n", sortedArr[0]);
    return 0;
}

Why Cases Matter

Algorithms को सिर्फ उनके worst case से compare करना misleading हो सकता है अगर वह worst case practice में शायद ही कभी होता हो, और सिर्फ best case से compare करना एक असली risk छुपा सकता है। तीनों cases को एक साथ देखना production उपयोग के लिए algorithm चुनने से पहले एक fair, complete picture देता है।

उदाहरण: Why Cases Matter

#include <iostream>
using namespace std;
int main() {
    // Comparing algorithms fairly means looking at best, worst, AND average --
    // not just one case, which can mislead.
    cout << "Best: O(1), Average: O(n), Worst: O(n) -- linear search summary" << endl;
    return 0;
}
public class Main {
    public static void main(String[] args) {
        // Fair comparison needs best, worst, AND average -- not just one case.
        System.out.println("Best: O(1), Average: O(n), Worst: O(n) -- linear search summary");
    }
}
# Fair comparison needs best, worst, AND average -- not just one case.
print("Best: O(1), Average: O(n), Worst: O(n) -- linear search summary")
#include <stdio.h>
int main() {
    /* Fair comparison needs best, worst, AND average -- not just one case. */
    printf("Best: O(1), Average: O(n), Worst: O(n) -- linear search summary\n");
    return 0;
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. सिर्फ best case quote करना, जैसे linear search के लिए O(1), जब लोग जिस guarantee पर भरोसा करते हैं वह worst case O(n) है।
  2. Quicksort के लिए average और worst case को mix up करना, जो average में O(n log n) है लेकिन pivot खराब होने पर O(n²)।
  3. यह मान लेना कि best case अक्सर होता है, जब यह realistic inputs पर बहुत दुर्लभ हो सकता है।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.