数据结构10:二分查找的递归与非递归表示与实现

来源:互联网 发布:foxmail迁移数据 编辑:程序博客网 时间:2024/06/15 09:23

1、给一个数组,如何测出数组的长度呢?或者测出最后一个有效元素的下标?

     例如:现在有一个数组int a[100],但是里面只有40个元素,那我需要怎样测出第四十个元素的下标呢?

     如果说,能知道数据元素的长度就可以不用指定high(最后一位有效元素的下标)了,下面是递归实现:

#include <stdio.h>#include <stdlib.h>#include <string.h>#define ERROR 0typedef int Status;typedef int ElemType;Status Find(ElemType *a,int high,int low,ElemType e){if (low <= high){int mid = (low + high)/2;if (a[mid]<e){Find(a,mid+1,low,e);}else if (a[mid] > e){Find(a,mid+1,high,e);}else if(a[mid] == e){return mid;}}elsereturn ERROR;}int main(){int i,pos;ElemType a[40];for (i = 0;i<40;i++){a[i] = i+1;}pos = Find(a,39,0,20);printf("%d",pos);system("pause");}
非递归实现,使用while循环就可以完成了!!

#include <stdio.h>#include <stdlib.h>#include <string.h>#define ERROR 0typedef int Status;typedef int ElemType;ElemType Find(ElemType *a,int high,ElemType e){int low = 0;int mid = (low + high)/2;while(low <= high){if (e == a[mid]){return mid;}else if (e > a[mid]){low = mid +1;mid = (low + high)/2;}else if (e <  a[mid]){high = mid - 1;mid = (low + high)/2;}}}int main(){int i,pos;ElemType a[40];for (i = 0;i<40;i++){a[i] = i+1;}pos = Find(a,39,20);printf("%d",pos);system("pause");}


0 0