Find the subscript of an element in an ordered array -> the half search algorithm / binary search algorithm (applicable to search when the number of array elements is large)

#define _CRT_SECURE_NO_WARNINGS 1

#include<stdio.h>
#include<string.h>

int main()
{
int k;
int a[] = {1,2,3,4,5,6,7,8,9,10 };
int sz = sizeof(a) / sizeof(a[0]) ;// Count the number of elements
int left = 0;//left subscript
int right = sz-1;//right subscript
scanf("%d", &k);

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

    if (a[mid] > k)
    {
        right = mid - 1;
    }
    else if (a[mid] < k)
    {
        left = mid + 1;
    }
    else
    {
        printf("下标是:%d\n", mid);
        break;
    }
}
if (left > right)
{
    printf("找不到此数\n");
}
return 0;

}

Guess you like

Origin blog.51cto.com/15068346/2586309