【C語言】二分查詢遞迴演算法
阿新 • • 發佈:2019-02-20
對有序的陣列使用二分查詢,可提高效率
二分查詢,下標由0開始,遞迴結束條件,data[p] == key || start >= end
int BinaryS(int *data,int start,int end,int key) { int result; int p = (start + end) / 2; if (data[p] == key || start >= end) { if (data[p] == key) { result = p; printf("\nyes! index is %d\n",p); return result; } else { result = -1; printf("\nno! %d\n",-1); return result; } //return result; } else { if (data[p] > key) { result = BinaryS(data, start, p, key); } else { result = BinaryS(data, p + 1, end, key); } return result; } }