二分查詢以及二分查詢的變形
//二分查詢:
#include <stdio.h> int binsearch(int x, int v[], int n); main() { int i, result, n; int wait; int x = 17; // 需要查詢的數值 int v[19]; // 定義一個數組 // 給陣列賦值 for(i = 0; i < 20; ++i) v[i] = i; /** for(i = 0; i < 20; ++i) printf("%d \n", v[i]); */ n = 20; result = binsearch(x, v, n); printf("%d", result); scanf("%d", &wait); } int binsearch(int x, int v[], int n) { int low, high, mid; low = 0; high = n - 1; while (low <= high) { mid = (low + high) / 2; if(x < v[mid]) high = mid - 1; else if (x > v[mid]) low = mid + 1; else return mid; // 看看迴圈執行了多少次 printf("mid = %d, low = %d, high = %d \n", mid, low, high); } return -1; }
// 二分查詢的變形:
#include<stdio.h> int main(){ int bs(int a[],int size,int p); int i,n,result; int p=11; int size=20; int a[19]; for(i=1;i<=20;i++) a[i]=i; result=bs (a,size,p); printf("%d",result); return 0; } int bs(int a[],int size,int p) {int l=0;int r=size-1; while(l<=r){ int mid=l+(r-l)/2; if(p==a[mid]) return mid; else if(p>a[mid]) l=mid+1; else r=mid-1; printf("mid = %d,l= %d,r = %d\n",mid,l,r); }
return -1; }