Upper Bound and Lower Bound are concepts used in mathematics and computer science, particularly in the context of sorting and searching within arrays.
Upper Bound:
The upper bound, in the context of an array, refers to the smallest element in the array which is greater than or equal to a given value. It is commonly used with sorted arrays.
For example, consider the following sorted array in ascending order:
[1, 3, 3, 5, 8, 8, 10]
If we want to find the upper bound for the value 3, we are looking for the smallest number in the array that is greater than or equal to 3. In this case, the upper bound would be the element 5 because it is the smallest number greater than 3.
In programming languages like C++, the standard library provides a function called upper_bound that can be used to perform this operation.
Lower Bound:
The lower bound, similarly, is the largest element in the array which is less than or equal to a given value.
For the same array:
[1, 3, 3, 5, 8, 8, 10]
If we want to find the lower bound for the value 3, we are looking for the largest number in the array that is less than or equal to 3. In this case, the lower bound would be the element 3 itself (the second occurrence of 3 in the array).
C++ also provides a function called lower_bound to find this.
Descending Array:
Now, if the array is sorted in descending order, the upper and lower bounds concepts still apply, but their roles are effectively reversed due to the order of the elements.
Consider the following array sorted in descending order:
[10, 8, 8, 5, 3, 3, 1]
For the value 3:
- The upper bound would now be the first element that is less than or equal to
3 when traversing from the start of the array. So the upper bound for 3 is 3 itself (the first occurrence).
- The lower bound would be the first element greater than
3 when traversing from the start. So the lower bound for 3 is 5.
Comparison:
In ascending arrays:
- Upper Bound: First element greater than or equal to the given value.
- Lower Bound: First element less than or equal to the given value.
In descending arrays:
- Upper Bound: First element less than or equal to the given value when traversing from the start.
- Lower Bound: First element greater than the given value when traversing from the start.
In both cases, the bounds are useful for determining ranges within a sorted array that match certain criteria, such as being within a particular value range. This can be especially useful in binary search algorithms and problems that require efficient searching.