Complete the code to perform a linear search for a target value in an array.
int linearSearch(int arr[], int n, int target) {
for (int i = 0; i < n; i++) {
if (arr[i] == [1]) {
return i;
}
}
return -1;
}The code checks if the current element arr[i] equals the target value we are searching for.
Complete the code to perform a binary search on a sorted array.
int binarySearch(int arr[], int left, int right, int target) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == [1]) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}The binary search compares the middle element arr[mid] with the target value to decide the next search range.
Fix the error in the binary search condition to correctly update the search range.
if (arr[mid] < [1]) { left = mid + 1; } else { right = mid - 1; }
The condition must compare arr[mid] with the target to decide which half to search next.
Fill both blanks to create a dictionary that maps each element to its index, then check if target exists.
std::unordered_map<int, int> indexMap; for (int i = 0; i < n; i++) { indexMap[[1]] = i; } if (indexMap.find([2]) != indexMap.end()) { return indexMap[[2]]; } else { return -1; }
i as the key instead of the element.The first blank should be the element arr[i] to map it to its index. The second blank is the target to check if it exists in the map.
Fill all three blanks to create a map comprehension that stores elements greater than 10 with their squares.
std::unordered_map<int, int> result; for (int [1] = 0; [1] < [3]; [1]++) { if (arr[[1]] [2] 10) { result[arr[[1]]] = arr[[1]] * arr[[1]]; } }
<.The loop variable is i. The condition checks if the element is greater than 10 using >. The loop runs while i < n.