Finding the maximum and minimum using less than O(2n) time
Given an array of integers, find the maximum and minimum of the array.
It seems trivial to find the maximum or the minimum.
Let n be the length of the array.
O(2n)
Using n - 1 comparisons, we are able to find the maximum. With another n - 1 comparisons, we are able to find the minimum. In order to find the minimum and maximum, the total runtime will be O(2n).
Could we do better?
How about sort the array first? Using the fastest sorting algorithm, the time complexity will be O(nlogn), which is more expensive than O(2n).
Actually, there is an algorithm with O(1.5n) time complexity.
This is how it works. We uses two variables curMax, curMin to keep track of the current maximum when we iterate through the array. The most important point is that each iteration, we will inspect two numbers in the array. Let's name them A and B. We compare A and B first. Then, we compare the larger one with the curMax, and update the curMax if necessary. Also, we compare the smaller one with curMin and update the curMin if necessary. For these two numbers, we do three comparisons. Since there are n numbers in the array, the total comparisons will be n / 2 * 3 = 1.5n.
O(2n)
Using n - 1 comparisons, we are able to find the maximum. With another n - 1 comparisons, we are able to find the minimum. In order to find the minimum and maximum, the total runtime will be O(2n).
Could we do better?
How about sort the array first? Using the fastest sorting algorithm, the time complexity will be O(nlogn), which is more expensive than O(2n).
Actually, there is an algorithm with O(1.5n) time complexity.
This is how it works. We uses two variables curMax, curMin to keep track of the current maximum when we iterate through the array. The most important point is that each iteration, we will inspect two numbers in the array. Let's name them A and B. We compare A and B first. Then, we compare the larger one with the curMax, and update the curMax if necessary. Also, we compare the smaller one with curMin and update the curMin if necessary. For these two numbers, we do three comparisons. Since there are n numbers in the array, the total comparisons will be n / 2 * 3 = 1.5n.
Comments
Post a Comment