递归与分治思想:治思想 && 折半查找法(迭代 && 递归)
1 //分治思想:将大问题拆成小问题逐一解决 2 //折半查找法:不断缩小一半查找的范围,知道达到目的,效率较高。 详情见:https://fishc.com.cn/thread-27964-1-1.html 3 4 //折半查找法(迭代) 5 #include<stdio.h> 6 7 int search(int str[], int n, int key); 8 9 int main(void) 10 { 11 int str[11] = {1,1,2,3,5,8,13,21,34,55,89}; 12 int n,adr; 13 14 printf("请输入你需要查找数据的关键字:"); 15 scanf("%d",&n); 16 printf("\n"); 17 18 adr = search(str,11,n); 19 if(adr != -1) 20 { 21 printf("查找成功,关键字%d所在的位置是:%d\n",n,adr); 22 } 23 else 24 { 25 printf("查找失败!\n"); 26 } 27 28 return 0; 29 } 30 31 int search(int str[], int n, int key) 32 { 33 int low,high,mid; 34 35 low = 0; 36 high = n-1; 37 mid = (low+high)/2; 38 39 while(low <= high) 40 { 41 if(key > str[mid]) 42 { 43 low = mid+1; 44 mid = (low+high)/2; 45 } 46 if(key < str[mid]) 47 { 48 high = mid-1; 49 mid = (low+high)/2; 50 } 51 if(key == str[mid]) 52 { 53 return mid; 54 } 55 } 56 57 return -1; 58 } 59 60 //折半查找法(递归算法) 61 #include<stdio.h> 62 63 int search(int str[], int low, int high, int key); 64 65 int main(void) 66 { 67 int str[11] = {1,1,2,3,5,8,13,21,34,55,89}; 68 int n,addr; 69 70 printf("请输入想要查找的关键字:"); 71 scanf("%d",&n); 72 73 addr = search(str,0,10,n); //0是low 10是high 74 if(addr == -1) 75 printf("查找失败!\n"); 76 else 77 printf("可喜可贺,可口可乐,你查找的关键字 %d 在位置 %d ",n,addr); 78 79 return 0; 80 } 81 82 int search(int str[], int low, int high, int key) 83 { 84 int mid; 85 if(low <= high) 86 { 87 mid = (low+high)/2; 88 if(str[mid] == key) 89 return mid; 90 else 91 { 92 if(key > str[mid]) 93 search(str,mid+1,high,key); 94 else 95 search(str,low,mid-1,key); 96 } 97 } 98 else 99 return -1; 100 }