2 min read

Analysis And Complexity of Algorithms | (Worst, Average and Best Cases)

The Best Case analysis is bogus. Guaranteeing a lower bound on an algorithm doesn’t provide any information as in the worst case, an algorithm may take years to run. For some algorithms, all the cases are asymptotically same, i.e., there are no worst and best cases.
Analysis And Complexity of Algorithms |  (Worst, Average and Best Cases)

We can have three cases to analyze an algorithm:
1) Worst Case
2) Average Case
3) Best Case
Let us consider the following implementation of Linear Search.

// C++ implementation of the approach #include using namespace std; // Linearly search x in arr[]. // If x is present then return the index, // otherwise return -1 int search(int arr[], int n, int x) { int i; for (i = 0; i < n; i++) { if (arr[i] == x) return i; } return -1; } // Driver Code int main() { int arr[] = { 1, 10, 30, 15 }; int x = 30; int n = sizeof(arr) / sizeof(arr[0]); cout << x << " is present at index " << search(arr, n, x); getchar(); return 0; }

Best case: Clearly the best case occurs when x is the first element in the array A. That is Θ(1)

Worst case: Clearly the worst case occurs when x is the last element in the array That is Θ(n)

Average case: Here we assume that searched element appear array A, and it is equally likely to occur at any position in the array. Here the number of comparisons can be any of numbers 1,2,3,…,n, and each number occurs with the probability p=1/n

The average case analysis is not easy to do in most of the practical cases and it is rarely done. In the average case analysis, we must know (or predict) the mathematical distribution of all possible inputs.

Analysis of Algorithms | Set 2 (Worst, Average and Best Cases) - GeeksforGeeks
A computer science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

#Complexity #Algorithm #BestCase #WorstCase #AverageCase #Probyto #ProbytoAI

Subscribe and follow us for latest news in Data Science and Machine learning and stay updated!
Facebook: https://facebook.com/probyto
Twitter: https://twitter.com/probyto
LinkedIn: https://linkedin.com/company/probyto
Instagram: https://instagram.com/probyto