Exercise IIX
Consider the following implementations of Arrays.reverse
:
public class Arrays {
public static <T> void reverse(T[] arr) {
T temp;
for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
public class Arrays {
public static <T> void reverse(T[] arr) {
int n = arr.length;
T[] tmp = (T[]) new Object[n];
for (int i = 0; i < n; i++) {
tmp[i] = arr[n - i - 1];
}
for (int i = 0; i < n; i++) {
arr[i] = tmp[i];
}
}
}
Exercise Complete the following table. Use Big-Oh notation to asymptotically describe time/space complexities.
Arrays.reverse | Time Complexity | Space Complexity | Input Space | Auxiliary Space |
---|---|---|---|---|
First program | ||||
Second prog. |
Solution
Arrays.revers | Time Complexity | Space Complexity | Input Space | Auxiliary Space |
---|---|---|---|---|
First program | $O(n)$ | $O(n)$ | $O(n)$ | $O(1)$ |
Second prog. | $O(n)$ | $O(n)$ | $O(n)$ | $O(n)$ |