Comparison of Searching Algorithms
Comparison of Searching Algorithms
O(log n) Logarithmic Binary Search while (low <= high) { mid = (low + high) / 2; if
Time (arr[mid] == key) return mid; else if (arr[mid] < key)
low = mid + 1; else high = mid - 1; }
O(n) Linear Time Linear Search for (int i = 0; i < n; i++) { if (arr[i] == key) return i; }
O(n log n) Linearithmic Merge Sort, Quick Sort void mergeSort(int arr[], int l, int r) { if (l < r) { int m =
Time (average case) l + (r - l) / 2; mergeSort(arr, l, m); mergeSort(arr, m + 1,
r); merge(arr, l, m, r); } }
O(n^2) Quadratic Bubble Sort, Selection for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if
Time Sort, Insertion Sort (arr[j] > arr[j+1]) swap(arr[j], arr[j+1]); } }
O(n^3) Cubic Time Floyd-Warshall for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) {
Algorithm for (int j = 0; j < n; j++) { dist[i][j] = min(dist[i][j],
dist[i][k] + dist[k][j]); } } }
O(2^n) Exponential Recursive Fibonacci, int fib(int n) { if (n <= 1) return n; return fib(n-1) +
Time Backtracking algorithms fib(n-2); }
O(n!) Factorial Traveling Salesman void permute(string str, int l, int r) { if (l == r) cout <<
Time Problem (Brute Force) str << endl; else { for (int i = l; i <= r; i++) {
swap(str[l], str[i]); permute(str, l+1, r); swap(str[l],
str[i]); } } }
Comparison of Sorting Algorithms
Sorting Running Best Case Average Case Worst Case Online/Offline In- Real-Time
Time Complexity Complexity Complexity Place/Out- Examples
Algorithm of-Place
Bubble Sort Slow O(n) O(n^2) O(n^2) Online In-Place Small datasets,
Educational
purposes
Insertion Moderate O(n) O(n^2) O(n^2) Online In-Place Sorting playing
cards, Small
Sort datasets
Selection Moderate O(n^2) O(n^2) O(n^2) Offline In-Place Selecting top
scores, Small lists
Sort
Merge Sort Fast O(n log n) O(n log n) O(n log n) Offline Out-of-Place Sorting linked lists,
External sorting
Quick Sort Very Fast O(n log n) O(n log n) O(n^2) (worst Offline In-Place Database sorting,
case) Compiler
optimizations
Shell Sort Fast O(n log n) O(n log n) O(n^2) Offline In-Place Optimized insertion
sort for medium
datasets
Radix Sort Very Fast O(nk) O(nk) O(nk) Offline Out-of-Place Sorting large
integers, Postal
sorting
Bucket Sort Very Fast O(n + k) O(n + k) O(n^2) Offline Out-of-Place Distributing exam
scores, Hash-based
sorting
Heap Sort Fast O(n log n) O(n log n) O(n log n) Offline In-Place Priority queues,
Scheduling
processes