Junior — Middle
Can you list the main algorithms for searching elements in an array?
sobes.tech AI
Answer from AI
Main algorithms for searching elements in an array:
-
Linear Search — sequentially traverses the array until the desired element is found. Simple to implement but slow for large arrays.
-
Binary Search — used on sorted arrays. Divides the array in half, compares the middle element with the target, and continues the search in the appropriate half. Operates in O(log n) time.
-
Interpolation Search — an improvement over binary search for uniformly distributed data, estimates the position of the target element using a formula.
Example of binary search in Java:
public int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left <= 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; // element not found
}