講解對(duì)象:C語言二分查找法 作者:融水公子 rsgz 前提:必須是有序的數(shù)據(jù) left=0; middle=(left+right); right=9; left>right 意味著找不到
#include<stdio.h> #include<stdlib.h> int main(int argc, const char* argv[]) { int score[10], x, i, flag = 0; int left = 0, middle, right = 9; printf("input ten numbers please:\n"); for (i = 0; i<10; i++) { scanf_s("%d", &score[i]); } printf("\n查找目標(biāo):\n"); scanf_s("%d", &x); while (left <= right) { middle = (left + right) / 2; if (score[middle] == x) { printf("數(shù)據(jù)存在 位置score[%d]\n", middle); flag = 1; break; } else if (score[middle]>x) {//數(shù)據(jù)在左邊 中間線賦值給右邊界 right = middle - 1; } else { //在右邊 中間線賦值給左邊界 left = middle + 1; } } if (flag == 0) { printf("數(shù)據(jù)不存在!\n"); } system("pause"); return 0; }
|