查找
1、折半查找法
# include <stdio.h> # define N 10 int main(void) { int i, num; int data[] = {13,15,23,29,30,31,38,45,56,69}; //在数组中存放10个整数; int low=0, high=N-1, mid; //定义数组中最低、最高及中间元素; printf("Please input a num: "); scanf("%d", &num); //输入查找的数字; for(i=0; i<N; ++i) { if(i%5 == 0 && i!=0) printf(" "); //每显示5行换行,以排列整齐; printf("data[%d]=%d ", i, data[i]); //输出赋值好的数组内的所有元素; mid = (low+high)/2; //计算出中间值; } while(low<=high) { mid = (low+high)/2; //计算中间值,第一次为(0+9)/2=4,data[4]为第五个数字30; if(num == data[mid]) { printf(" Find %d, It is data[%d]!", num, mid); break; } else if(num > data[mid]) low = mid+1; //注意:是mid+1而非low+1; else high = mid-1; } if(low>high) //无该数字,查找失败。 printf(" %d is not in data[]", num); printf(" low = %d, high = %d", low, high); putchar(' '); return 0; }
2、在线性链表上的顺序查找算法
LinkNode *seqSearch(LinkList &L,DataType x) { LinkNode *p = L; while(p != NULL && p->data != x) p = p->link; return p; }
3、设计一个在顺序表上执行顺序查找的递归算法
int seqSearchl(seqList &L, DataType x,int loc) { if(loc>=L.n) return -1; else if(L.data[loc] == x) return loc; else return seqSearch(L,X,loc+1); };