Junior — Middle
How is the efficiency of element search within an array evaluated, and what factors influence its complexity?
sobes.tech AI
Answer from AI
The efficiency of element search in an array is evaluated using the search algorithm's time complexity.
- Linear Search: sequentially checking each element. Worst-case complexity — O(n), where n is the number of elements.
- Binary Search: used on sorted arrays. Complexity — O(log n).
Factors affecting search complexity:
- Data structure: arrays allow quick access by index, but searching without sorting requires traversal.
- Array sortedness: binary search is only possible if the array is sorted.
- Array size: the larger the number of elements, the longer the search when using linear traversal.
Example of binary search in C#:
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
}