1.1 Based on the following code for Bubble-sort, analyze the algorithm's time complexity:
void bubbleSort(int arr[], int n) { int i, j, temp; for(i = 0; i < n - 1; i++) { for(j = 0; j < n - i - 1; j++) { if(arr[j] > arr[j + 1]) { // swap the elements temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } }
1.2 Based on the following code for Selection sort, analyze the algorithm's time complexity:
void selectionSort(int arr[], int n) { int i, j, min_idx, temp; for (i = 0; i < n - 1; i++) { min_idx = i; for (j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // swap the min element with the first element temp = arr[min_idx]; arr[min_idx] = arr[i]; arr[i] = temp; } }
Consider the following search algorithm of a value v in a sorted array arr:
int search(int arr[], int lo, int hi, int v) { int mid = (lo + hi) / 2; if (arr[mid] == v) return mid; if (lo == hi) return -1; if (arr[mid] > v) return search(arr, lo, mid, v); else return search(arr, mid, hi, v); }
2.1 Determine the recurrence for the search algorithm above.
2.2 Solve the recurrence using the Master Method.
2.3 Solve the recurrence using the Trees Method.
2.4 Solve the recurrence using the Substitution Method.
Consider the following modification to 'search' (which may not make sense in practice):
int search(int arr[], int lo, int hi, int v) { if (!is_sorted(arr, lo, hi)) return -1; int mid = (lo + hi) / 2; if (arr[mid] == v) return mid; if (lo == hi) return -1; if (arr[mid] > v) return search(arr, lo, mid, v); else return search(arr, mid, hi, v); }
3.1 In what time can we check if an array is sorted?
3.2 What is the new recurrence for search?
3.3 Solve the recurrence, using all three methods.
4.1 Substitution method does not work. Solve $ T(n) = 2 T($ $ n \over 2$ $ ) + 1$ .
4.2 Un-balanced trees. Solve via the tree and substitution methods: $ T(n) = T($ $ n \over 4$ $ ) + T($ $ 3n \over 4$ $ ) + n$ .
4.3 Solve $ T(n) = 2 T($ $ n \over 2$ $ ) + n ^ 2$ .
4.4 Look up the Hanoi towers problem. Determine the number of steps necessary to solve it.
4.5 Consider the following algorithm:
int fibo(int n) { if (n <= 1) return n; return fibo(n - 1) + fibo(n - 2); }
Determine its complexity with regard to the size of the input.
4.6 Solve $ T(n) = \sqrt n * T(\sqrt n) + n$ .