Recursive implementation of binary lookup method

Source: Internet
Author: User

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;
}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.