Location>code7788 >text

C# Binary Lookup Algorithm

Popularity:470 ℃/2024-10-12 13:04:30
public class Dichotomous Lookup Algorithm
    {
        /// <summary>
/// Dichotomous lookup algorithm
        /// </summary>
/// <param name="arr"> arr is a sorted array </param>
/// <param name="target"> target is the target value to be looked up </param>
/// <returns> the index of the target value in the array, or -1 if not found</returns>.
        public static int BinarySearch(int[] arr, int target)
        {
int left = 0; // define left pointer
int right = - 1; // define right pointer

            while (left <= right)
            {
// Calculate the index of the middle element
                int mid = left + (right - left) / 2;

                if (arr[mid] == target)
                {
// If the middle element is equal to the target value
return mid; // find successful, return index
                }
                else if (arr[mid] < target)
                {
// if the target value is less than the middle element, lookup in the left half
                    left = mid + 1;
                }
                else
                {
// if the target value is greater than the middle element, lookup in the right half
                    right = mid - 1;
                }
            }

// target not found, return -1
            return -1;
        }

        public static void BinarySearchRun()
        {
int[] arr = { 1, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59 }; //note: the array here is a sorted array
int target = 31; //need to find the target value

int result = BinarySearch(arr, target); //call binary search method

            if (result == -1)
            {
("Element not found").
            }
            else
            {
($"Element found, index is: {result}, value is: {arr[result]}");;
            }
        }
    }