碼海拾遺:二分查找
阿新 • • 發佈:2017-10-04
art d+ 位置 size urn int blog chan hang
二分查找法(Binary Search):在有序數組中查找某一特定元素位置的搜索算法
實現:
1 //遞歸二分查找 2 template <typename T> 3 int binarySearch(T *arr, int start, int end, T key) 4 { 5 if (start > end) 6 return -1; 7 8 int mid = (start + end) / 2; 9 if (arr[mid] < key) 10 return binarySearch(arr, mid+1, end, key); 11 else if (arr[mid] > key) 12 return binarySearch(arr, start, mid-1, key); 13 else 14 return mid; 15 } 16 17 //非遞歸二分查找 18 template <typename T> 19 int binarySearch(T *arr, int arrSize, T key) 20 { 21 if (NULL == arr || arrSize == 0) 22 return -1; 23 24 int start = 0; 25 int end = arrSize - 1; 26 int mid = 0; 27 28 while (start <= end) 29 { 30 mid = (start + end) / 2; 31 if (arr[mid] == key) 32 return mid; 33 else if (arr[mid] < key) 34 start = mid + 1; 35 else 36end = mid - 1; 37 } 38 return -1; 39 } 40 41 template <typename T> 42 int change(T& a, T& b) 43 { 44 T tmp = a; 45 a = b; 46 b = tmp; 47 return 0; 48 } 49 50 template <typename T> 51 int sort(T* arr, int arrSize) 52 { 53 if (NULL == arr || arrSize == 0) 54 return -1; 55 for (int i = 0; i < arrSize; ++i) 56 { 57 for (int j = 0; j < arrSize; ++j) 58 { 59 if (arr[i] < arr[j]) 60 change(arr[i], arr[j]); 61 /*{ 62 int tmp = arr[i]; 63 arr[i] = arr[j]; 64 arr[j] = tmp; 65 }*/ 66 } 67 } 68 return 0; 69 }
碼海拾遺:二分查找