How to write the code for the binary search algorithm in C language?

Here is an example code of a basic binary search algorithm in C language.

#include <stdio.h>

int binarySearch(int arr[], int left, int right, int target) {
    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; // 表示未找到
}

int main() {
    int arr[] = {1, 3, 5, 7, 9, 11, 13, 15};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 7;
    
    int result = binarySearch(arr, 0, n - 1, target);
    
    if (result == -1) {
        printf("Element not found\n");
    } else {
        printf("Element found at index %d\n", result);
    }
    
    return 0;
}

In this example code, the binarySearch function takes a sorted array, the left and right boundaries of the array, and a target element as parameters, and returns the index of the target element. In the main function, we declare a sorted array called arr, and then call the binarySearch function to search for the target element 7. If the target element is found, it will print out the index of the target element, otherwise it will print out “Element not found”.

Leave a Reply 0

Your email address will not be published. Required fields are marked *