Non-recursive method:
#include <stdio.h> #include <stdlib.h> #define &NBSP;NUMBER&NBSP;6&NBSP;INT&NBSP;BINSEARCH ( Int x, int *arr, int left, int right); Int main () {int x = 0, inter = 0;int arr[number] = { 1, 5, 12, 36, 45 , 98 };/** printf ("Please enter the number:> found");* for (int i = 0; i < sizeof (arr) / sizeof (arr[0]), i++) *scanf_s ("%d", &arr[i]); */printf (" Please enter the number you want to find:> "), scanf_s ("%d ", &x); Inter = binsearch (x, arr, 0, sizeof (arr) / sizeof (arr[0]) - 1);if (inter == -1) printf ("Did not find the number you are looking for!") \ n "); elseprintf (" The number you are looking for is%d and the location is%d\n ", x, inter); System (" pause "); return 0;} Int binsearch (int x, int *arr, int left, int right) {int mid = 0;while (left <= right) {mid = left - (left - right) / 2;if (x == * (arr + mid))/ * found the */{return mid;} else if (x < * (arr + mid)/* large */{right = mid - 1;} else/* small */{left = mid + 1;}} return -1; /* not found * *}
Recursive (cannot output the position of the number you want to find in the original array):
#include <stdio.h> #include <stdlib.h>int binsearch (Int x, int *arr, int n); Int main () {int x = 0, inter = 0;int arr[] = { 1, 5, 12, 36, 48, 98 };p rintf ("Please enter the number of:> you want to find") scanf_s ("%d", &x) Inter = binsearch (x, arr, sizeof (arr)/sizeof (arr[0]);if (inter == -1) printf ("Did not find the number you are looking for!") \ n "); elseprintf (" found the number%d\n you are looking for ", x); System (" pause "); return 0;} Int binsearch (int x, int *arr, int n) {int mid = (n - 1) / 2;if (n <= 0) return -1;else if (x == * (arr + mid)) /* found */return mid;else if (x < * (ARR&NBSP;+&NBSP;MID))/* A bit large */{ Return binsearch (X,&NBSP;ARR+MID-1,&NBSP;MID);/* The next time the array length is mid */}else if (x > * (Arr + mid)) /* a little bit small */{return binsearch (X, arr+mid+1, mid);}}
Binary find------Find a specific number in an ordered array of ascending order