Realization idea:
Given a set of sorted arrays, starting with the elements in the middle of the array and comparing the elements to find
If the middle element is larger than the element to find, narrow the look to the left half of the middle element (the target element belongs to this range)
If the middle element is smaller than the element you are looking for, narrow the lookup to the right half of the middle element (the target element belongs to this range)
Recursive implementations:
#include <iostream>
#include <stdlib.h>
using namespace std;
int testarray[1000];
int findelement (int array[], int S, int N, int X) { //n = array size if
(S > N) //if s = = n Then the subscript element is either the result or the element to be found Does not exist
{
cout << "element not found!" << Endl;
return-1;
}
int mid = (S + N)/2;
if (array[mid] = = X)
return array[mid]; Get results returned by
else if (Array[mid] > X)
findelement (array, 0, Mid, X); Find the
else if (Array[mid] < X)
findelement (array, mid+1, N, X) starting from the left half of the section; Starting from the right half, find the
}
void Main () {for
(int i = 0; i < ++i) {
testarray[i] = i;
}
int size = sizeof (Testarray)/sizeof (int);
int calresult = findelement (testarray, 0, size-1, 999);
cout << calresult << Endl;
System ("PAUSE");
return;
}