现在的位置: 首页 > 综合 > 正文

2008秋-计算机软件基础- 第四章- 顺序查找,二分查找

2012年07月11日 ⁄ 综合 ⁄ 共 1502字 ⁄ 字号 评论关闭
/*---------------------------------------------------------
Title: 顺序查找  
Author : Eman Lee
----------------------------------------------------------
*/
#include
<stdio.h>
//定义顺序存储线性表的结点结构
struct node
{
    
int  key;//关键字
       int  other; //非关键字
}; 

int SequencSearch(struct node numbers[],int length, int value)
{
 
//顺序查找,在numbers[]中查找value,表长length 
 
//成功返回位置(0~length-1),失败返回-1。
    int i;
    
for(i=0;i<length;i++)
    {
         
if(numbers[i].key==value)
              
return i;
    }
    
return -1;
}

void main()
{
    
struct node s[5]={{1,80},{2,75},{3,60},{4,89},{5,100}};
    
int position;
    position
=SequencSearch(s,5,3);
    
//position=SequencSearch(s,5,10);
    printf("position=%d\n",position);

}

/*---------------------------------------------------------
Title: 二分查找  
Author : Eman Lee

----------------------------------------------------------
*/
#include
<stdio.h>
//定义顺序存储线性表的结点结构
struct node
{
    
int  key;//关键字
       int  other; //非关键字
}; 

int binsearch(struct node r[],int n,int x) 
/*在长度为n的升序线性表上查找关键字为x的元素*/
int low,high,mid;
  low
=1;  high=n; 
/*设置查找区间左、右端点的初值*/
  
while(low<=high) /*当查找区间非空时进行查找*/
   { mid
=(low+high)/2/*求出区间中间位置mid的值*/
     
if(x==r[mid].key)  return(mid); 
/*查找成功时返回元素所在的位置*/
     
else 
      { 
if(x<r[mid].key)  high=mid-1/*缩小查找区间*/
        
else  low=mid+1;
      }
    }
  
return(0);  /*查找失败时返回0值*/
 } 
/*binsearch*/

void main()
{
    
struct node s[6]={{0,0},{1,80},{2,75},{3,60},{4,89},{5,100}};
    
int position;
    
//position=binsearch(s,5,3);
    position=binsearch(s,5,10);
    printf(
"position=%d\n",position);

}

抱歉!评论已关闭.