标签:折半查找
非递归法:
#include <stdio.h> #include <stdlib.h> #define number 6 int binsearch(int x, int *arr, int left, int right); int main() { int x = 0, inter = 0; int arr[number] = { 1, 5, 12, 36, 45, 98 }; /* * printf("请输入可查找到的数:> "); * for (int i = 0; i < sizeof(arr) / sizeof(arr[0]);i++) * scanf_s("%d", &arr[i]); */ printf("请输入您要查找的数:> "); scanf_s("%d", &x); inter = binsearch(x, arr, 0, sizeof(arr) / sizeof(arr[0]) - 1); if (inter == -1) printf("没有找到你要查找的数!\n"); else printf("您要查找的数是%d,且位置为%d\n", x, inter); system("pause"); return 0; } int binsearch(int x, int *arr, int left, int right) { int mid = 0; while (left <= right) { mid = left - (left - right) / 2; if (x == *(arr + mid)) /*找到了*/ { return mid; } else if (x < *(arr + mid)) /*偏大*/ { right = mid - 1; } else /*偏小*/ { left = mid + 1; } } return -1; /*没找到*/ }
递归法(不能输出要查找的数字在原数组中的位置):
#include <stdio.h> #include <stdlib.h> int binsearch(int x, int *arr, int n); int main() { int x = 0, inter = 0; int arr[] = { 1, 5, 12, 36, 48, 98 }; printf("请输入您要查找的数:> "); scanf_s("%d", &x); inter = binsearch(x, arr, sizeof(arr)/sizeof(arr[0])); if (inter == -1) printf("没找到您要查找的数!\n"); else printf("找到了您要查找的数%d\n", x); system("pause"); return 0; } int binsearch(int x, int *arr, int n) { int mid = (n - 1) / 2; if (n <= 0) return -1; else if (x == *(arr + mid)) /*找到了*/ return mid; else if(x < *(arr + mid)) /*有点大 */ { return binsearch(x, arr+mid-1, mid);/*下一次数组长度为mid */ } else if (x > *(arr + mid)) /*有点小*/ { return binsearch(x, arr+mid+1, mid); } }
折半查找------在一个升序的有序数组中查找某个具体的数字
标签:折半查找
原文地址:http://10740026.blog.51cto.com/10730026/1702274