int linear_search(int array[], int size, int key) { int i; for (i = 0; i < size; i++) { if (array[i] == key) return i; } return -1; }
int binary_search(int array[], int size, int key) { int mid, hi, low; low = 0; hi = size-1; mid = (low + hi) / 2; while (low <= hi) { if (array[mid] == key) return mid; else if (array[mid] < key) { low = mid + 1; mid = (low + hi) / 2; } else { hi = mid - 1; mid = (low + hi) / 2; } } return -1; } }
void selection_sort(int array[], int size) { int i, j; int min; int temp; for (i = 0; i < size-1; i++) { min = i; for (j = i+1; j < size; j++) { if (array[j] < array[min]) { min = j; } } if (i != min) { temp = array[i]; array[i] = array[min]; array[min] = temp; } } }
Put graphically, it means that after a certain point on the x axis, as we go right, the curve for f(n) will always be higher than g(n).
O(T1) + O(T2) = O(T1 + T2) = max(O(T1), O(T2))
O(T1)O(T2) = O(T1T2)
Complexity | Example | algorithm |
---|---|---|
O(1) | Fetching an element from an array | return ith element |
O(log n) | Splitting a set of data in half with one operation and throwing away one of the two halves | binary search |
O(n) | Traversing a set of data once | linear search |
O(n log n) | Splitting a set of data in half repeatedly and traversing each half | quicksort |
O(n2) |
|
|
O(2n) | Generating all possible subsets of a set of data | knapsack problem where you try to take a set of weights and divide them so that the two knapsacks have the minimal possible difference in weight--best known algorithm requires you to take all subsets of weights and put each set in knapsack 1 and the remainder in knapsack 2 |
O(n!) | Generating all possible permutations of a set of data | traveling salesman problem--salesman must visit each city once and you want to find the cheapest total fare. One algorithm is to generate all permutations of cities and test each permutation for the cheapest fare. |