Title Description
For an ordered array, we usually use a binary lookup to locate an element, write a binary lookup algorithm, and find the specified element in the array.
Given an integer array A and its size n, given the element to find Val, return its position in the array (starting at 0), or 1 if the element does not exist. If the element appears more than once, return to the first occurrence of the position.
Enter a description
The first line enters N, which represents the length of the array
Enter n number in the second line
The third line enters the key value to find
Output description
Outputs an integer that represents the subscript of the array position where key is located, starting with 0
Input sample
5 1 3 5 7 9 5
Output sample
2
Test code
#include <stdio.h>#include<stdlib.h>intGetPos (int*a,intNintkey) { intLow , high, mid; Low=0, high = n-1; while(High >=Low ) {Mid= (low + high)/2; if(Key >A[mid]) { Low= Mid +1; } Else if(Key <A[mid]) { High= Mid-1; } Else { while(A[mid] = = A[mid-1]) {Mid--; } returnmid; } } return-1;}intMain () {intN, Key; scanf ("%d", &N); int*a = (int*)calloc(N,sizeof(int)); for(inti =0; I < n; i++) {scanf ("%d", &A[i]); } scanf ("%d", &key); printf ("%d\n", GetPos (A, n, key)); Free(a); return 0;}
Two-point Search