Nathan Sprague
1/30/23
I need to write Python code to find the largest gap between any pair of numbers in a list:
Our textbook suggests that we should count “constant time operations”
\(W(n) = 3n + 3\)
How about for this implementation?
Does this mean the second implementation is faster?
\(\log_2 1 = 0\)
\(\log_2 2 = 1\)
\(\log_2 4 = 2\)
\(\log_2 8 = 3\)
…
\(\log_2 4,000,000,000 = ??\)
private static int binarySearch(int[] numbers, int key) {
int low = 0;
int high = numbers.length - 1;
int mid;
// Loop until "low" passes "high"
while (high >= low) {
mid = (high + low) / 2;
if (numbers[mid] < key) {
low = mid + 1;
}
else if (numbers[mid] > key) {
high = mid - 1;
}
else {
return mid;
}
}
return -1; // not found
}
Result:
\(n\) | total equality checks |
---|---|
1 | 1 |
2 | 2 |
4 | 3 |
8 | 4 |
(For non-powers-of-two \(\lfloor\log_2 n\rfloor + 1\))
Consider the following (very) informal definitions:
A reasonably fast computer can perform 1,000,000,000 operations per second
A reasonably short period of time is one second
A program is good enough if it can process 1,000,000 items in a reasonably short period of time on a reasonably fast computer.
Assume that \(T(n)\) is a function that describes the number of operations required for program A. Select the first true statement from the following list.
Consider the following (very) informal definitions:
A reasonably fast computer can perform 1,000,000,000 operations per second
A reasonably short period of time is one second
A program is not totally useless if it can process 100 items in a reasonably short period of time on a reasonably fast computer.
Assume that \(T(n)\) is a function that describes the number of operations required for program A. Select the first true statement from the following list.