Complete the code to perform a linear search that returns the index of the target or -1 if not found.
int LinearSearch(int[] arr, int target) {
for (int i = 0; i < arr.Length; i++) {
if (arr[i] == [1]) {
return i;
}
}
return -1;
}The code compares each element arr[i] with the target value to find a match.
Complete the code to perform a binary search on a sorted array to find the target value.
int BinarySearch(int[] arr, int target) {
int left = 0;
int right = arr.Length - 1;
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 to decide which half to search next.
Fix the error in the binary search code: complete the condition to continue the loop correctly.
int BinarySearch(int[] arr, int target) {
int left = 0;
int right = arr.Length - 1;
while (left [1] right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}The loop should continue while left is less than or equal to right to check all possible positions.
Fill both blanks to create a dictionary comprehension that maps words to their lengths only if length is greater than 3.
var result = new Dictionary<string, int>(); foreach (var word in words) { if (word.[1] > 3) { result[word] = word.[2]; } }
In C#, string length is accessed by the Length property without parentheses.
Fill all three blanks to create a dictionary that maps uppercase words to their lengths only if length is greater than 4.
var result = new Dictionary<string, int>(); foreach (var word in words) { if (word.[1] > 4) { result[word.[2]()] = word.[3]; } }
Use Length property to check length, ToUpper() method to convert word, and Length property again for value.
