标签:查找算法 search inf can err sys ret lse 算法
Part 1
1. A
Part2
1.ex2_1_1.cpp
// 练习:使用二分查找,在一组有序元素中查找数据项 // 形参是数组,实参是数组名 #include <stdio.h> #include <stdlib.h> const int N=5; int binarySearch(int x[], int n, int item); // 函数声明 int main() { int a[N]={2,7,19,45,66}; int i,index, key; printf("数组a中的数据:\n"); for(i=0;i<N;i++) printf("%d ",a[i]); printf("\n"); printf("输入待查找的数据项: "); scanf("%d", &key); // 调用函数binarySearch()在数组a中查找指定数据项item,并返回查找结果给index // 补足代码① // ××× index=binarySearch(a,N,key); if(index>=0) printf("%d在数组中,下标为%d\n", key, index); else printf("%d不在数组中\n", key); system("pause"); return 0; } //函数功能描述: //使用二分查找算法在数组x中查找特定值item,数组x大小为n // 如果找到,返回其下标 // 如果没找到,返回-1 int binarySearch(int x[], int n, int item) { int low, high, mid; low = 0; high = n-1; while(low <= high) { mid = (low+high)/2; if (item == x[mid]) return mid; else if(item<x[mid]) high = mid - 1; else low = mid + 1; } return -1; }
2. ex2_1_2.cpp
#include <stdio.h> #include <stdlib.h> #define N 10 int fun(int *a,int m) { int low = 0, high = N-1, mid; /*************ERROR**************/ while(low <=high) { mid = (low+high)/2; /*************ERROR**************/ if(m <*(a+mid)) high = mid-1; /*************ERROR**************/ else if(m >*(a+mid)) low = mid+1; else return(mid); } return(-1); } int main() { int i,a[N]={-3,4,7,9,13,24,67,89,100,180},k,m; printf("a数组中的数据如下:\n"); for(i=0;i<N;i++) printf("%d ",a[i]); printf("\nEnter m: \n"); scanf("%d",&m); /*************ERROR**************/ k = fun(a,m); if (k>=0) printf("m=%d,index=%d\n",m,k); else printf("Not be found!\n"); system("pause"); return 0; }
3.ex2_2_1.cpp
Part3
标签:查找算法 search inf can err sys ret lse 算法
原文地址:https://www.cnblogs.com/ywq1823640661/p/12043570.html