二分查找[递归+循环]
使用递归实现二分查找
1 #include <stdio.h> 2 3 void binary_sort(int a[], int num, int head, int tail) 4 { 5 if (head <= tail) { 6 int middle = (head+tail)/2; 7 if (num>a[middle]) 8 binary_sort(a, num, middle+1, tail); 9 else if (num<a[middle]) 10 binary_sort(a, num, head, middle-1); 11 else if (num == a[middle]) 12 printf("找到a[%d]=%d", middle, a[middle]); 13 } 14 else { 15 printf("未找到%d", num); 16 } 17 } 18 19 int main() 20 { 21 int a[15]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,16}; 22 int num=18; 23 int head = 0; 24 int tail = 14; 25 binary_sort(a, num, head, tail); 26 27 return 0; 28 }
使用循环实现二分查找
1 #include <stdio.h> 2 3 void binary_sort(int a[], int num, int head, int tail) 4 { 5 int middle = (head+tail)/2; 6 while (head <= tail) { 7 if (num > a[middle]) { 8 head = middle+1; 9 middle = (head+tail)/2; 10 } else if (num < a[middle]) { 11 tail = middle-1; 12 middle = (head+tail)/2; 13 } else { 14 printf("找到a[%d]=%d", middle, a[middle]); 15 return ; 16 } 17 } 18 printf("未找到%d", num); 19 } 20 21 int main() 22 { 23 int a[15]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,16}; 24 int num=18; 25 int head = 0; 26 int tail = 14; 27 binary_sort(a, num, head, tail); 28 29 return 0; 30 }