Binary Search, Binary Search Algorithm
The normal binary search, the head and tail are constantly replaced, and each time the half is cut
# Define _ CRT_SECURE_NO_WARNINGS # include <stdlib. h> # include <stdio. h> # define N 1024 void search (int a [N], int num) // Binary search {int tou = 0; int wei = N-1; int zhong; int flag =-1; int ci = 0; while (tou <= wei) {zhong = (tou + wei)/2; if (num = a [zhong]) {ci ++; printf ("found, a [% d] = % d", zhong, num); flag = 1; break ;} else if (num> a [zhong]) {tou = zhong + 1 ;}else {wei = zhong-1 ;}} if (flag =-1) {printf ("not found ");}}
Returns a list of half of the query results by using the two-part query method.
Void searchL (int a [N], int num) // returns the query result of {int tou = 0; int wei = N-1; int zhong; int flag =-1; int ci = 0; while (tou <= wei) {zhong = tou + (wei-tou) * 1.0 * (num-a [tou]) /(a [wei]-a [tou]); if (num = a [zhong]) {printf ("found, a [% d] = % d, % d ", zhong, num, ++ ci); flag = 1; break;} else if (num> a [zhong]) {tou = zhong + 1 ;} else {wei = zhong-1; }}if (flag =-1) {printf ("not found") ;}} void main () {int a [N]; for (int I = 0; I <N; I ++) {a [I] = I; printf ("% d", I) ;} int num; scanf ("% d", & num); searchL (a, num); system ("pause ");}