最近在牛客網刷題,有一道題目是實現二分查找算法,由此便在咖啡店寫了段代碼,實現這個簡單的算法。但同時本身還有一個問題(見最後),但願有朋友能幫忙解答。後期若是本身知道答案,我會本身更新在此。ios
一. 算法介紹算法
優勢:比較次數少,查找速度快,平均性能好;app
缺點:要求待查表爲有序表,且插入刪除困難。性能
適用:不常常變更而查找頻繁的有序列表。spa
時間複雜度:o(log(n))code
二. 算法代碼實現(C++) blog
1 // BinarySearch.cpp : Defines the entry point for the console application. 2 3 #include "stdafx.h" 4 #include <iostream> 5 6 using namespace std; 7 8 //compare function 9 int compare(const void *val1, const void *val2) 10 { 11 int iVal1 = *(int*)val1; 12 int iVal2 = *(int*)val2; 13 14 cout << "Compare: " << iVal1 << ", " << iVal2 << endl; 15 16 if (iVal1 > iVal2) 17 { 18 return 1; 19 } 20 else if (iVal1 == iVal2) 21 { 22 return 0; 23 } 24 else 25 { 26 return -1; 27 } 28 } 29 30 //nel: num of element, width: every element size 31 void *bsearch(const void *key, const void *base, size_t nel, size_t width, int (*compar)(const void*, const void *)) 32 { 33 int pos = nel / 2; 34 35 cout << "Position: " << pos << endl; 36 37 int result = (*compar)(key, (int *)base + pos); 38 39 if (pos == 0) 40 { 41 return result == 0 ? (void *)base : NULL; 42 } 43 44 if (result > 0) 45 { 46 return bsearch(key, (int *)base + pos + 1, pos, width, compar); 47 } 48 else if (result == 0) 49 { 50 return (void *)base; 51 } 52 else 53 { 54 return bsearch(key, base, pos, width, compar); 55 } 56 } 57 58 int _tmain(int argc, _TCHAR* argv[]) 59 { 60 int array[] = { 1, 3, 5, 6, 11, 13, 17, 29, 44, 66, 79, 99, 111 }; 61 int arrayNum = sizeof(array) / sizeof(*array); 62 cout << "Array Element Num: " << arrayNum << endl; 63 64 int searchVal = 13; 65 cout << "Search Value: " << searchVal << endl; 66 67 int *result = (int *)bsearch(&searchVal, array, arrayNum, sizeof(*array), compare); 68 69 cout << "Result: " << (result == NULL ? "Not Found" : "Found") << endl; 70 71 system("pause"); 72 return 0; 73 }
運行顯示正確。接口
三. 問題element
這裏本身有一個小問題,就是算法接口中的size_t width參數我並無用到,同時我假設元素都是INT型。請問這裏該如何修改,既能用到width,又不用假設元素爲特定類型?謝謝。it
Best Regards
Kevin Song