Problems
[Divide and Conquer Algorithm]
This is an algorithm (method) that solves a problem by breaking it down into smaller sub-problems when the size of the original problem is too large to handle at once.
Representative examples include Binary Search, Quick Sort, and Merge Sort.
[Binary Search]
The Binary Search algorithm is a type of divide-and-conquer algorithm used to quickly find a target value or its position (index) within a sorted data list.
Suppose we have a sorted array A[] and we want to find a target value. Let the index of the first element be low and the index of the last element be high.
Binary Search Process
Calculate the middle index (
mid) of the current search range:mid = (low + high) / 2
Compare the value at A[mid] with the
target:(1) If A[mid] == target: You have found the target or its position.
(2) If A[mid] < target: Adjust the search range by setting low = mid + 1.
(3) If A[mid] > target: Adjust the search range by setting high = mid - 1.
Repeat steps 1 and 2 as long as the search range exists and the target has not been found.
If low > high (no search range remains), the target value does not exist in the array.
Performance
In this process, the search range is reduced by half or more in every loop. The following table compares the number of data elements to the maximum number of searches required:
Number of Data (N) | Max Searches |
1 | 1 |
2 ~ 3 | 2 |
4 ~ 7 | 3 |
8 ~ 15 | 4 |
16 ~ 31 | 5 |
As the amount of data doubles, the number of searches increases by only 1. Therefore, the number of searches relative to the number of data can be generalized as log_2(n) + 1. This shows significantly better performance compared to Sequential Search.
[Binary Search Pseudocode]
Loop Version
binarySearch (A[], low, high, target):
while low <= high:
mid = (low + high) / 2
if A[mid] == target:
return mid
if A[mid] > target:
high = mid - 1
else:
low = mid + 1
return -1
Recursive Version
binarySearchRecur (A[], low, high, target):
if low > high:
return -1
mid = (low + high) / 2
if A[mid] == target:
return mid
if A[mid] > target:
return binarySearchRecur(A, low, mid - 1, target)
return binarySearchRecur(A, mid + 1, high, target)
[Problem]
Given
Input
In the first line,
In the second line,
In the third line,
In the fourth line,
Output
For
Assume that the first element of the array is stored at index
If the value is not found, print
Example #1
5
1 2 3 4 5
3
-5 5 2
-1 4 1
Example #2
8
-7 -5 -3 0 2 4 6 8
5
-3 6 -7 0 8
2 6 0 3 7