Sobes.tech
Junior — Middle

Could you provide an example of a method for searching for a specific element in a sorted data array?

sobes.tech AI

Answer from AI

Binary search algorithm is often used to find an element in a sorted array, which operates in logarithmic time O(log n).

Example implementation of binary search in C#:

int BinarySearch(int[] sortedArray, int target) {
    int left = 0;
    int right = sortedArray.Length - 1;

    while (left <= right) {
        int mid = left + (right - left) / 2;

        if (sortedArray[mid] == target) {
            return mid; // element found
        } else if (sortedArray[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return -1; // element not found
}
Could you provide an example of a method for… - sobes.tech