建立一个递增的有序表(用顺序表作存储结构),用折半查找的方法对其实施查找。
顺序表的类型描述:
#define MAXSIZE 50
typedef int ElemType;
typedef struct
{
ElemType *R;
int length;
} SSTable;
输入格式:
第一行输入一个整数n,表示顺序表的元素个数。
第二行行输入n个递增的数字,依次为表内元素值。
第三行输入一个要查找的值。
输出格式:
输出这个值在表中的位置。如果没有找到,输出NOT FOUND
。
输入样例:
5
2 4 6 8 10
6
输出样例:
3
输入样例:
5
2 4 6 8 10
18
输出样例:
NOT FOUND
代码如下:
/*#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 50
typedef struct {
int key;
}SElemType;
typedef struct
{
SElemType *R;
int length;
} SSTable;
int Search_Bin(SSTable ST, int key);
int main()
{
SSTable ST;
scanf("%d",&ST.length);
ST.R = (SElemType*) malloc((ST.length+1)*sizeof(SElemType));
int i;
for(i=1;i<=ST.length;i++){
scanf("%d",&ST.R[i].key);
}
int key;
scanf("%d",&key);
int pos = Search_Bin(ST, key);
if(pos == -1) puts("NOT FOUND");
else printf("%d\n", pos);
return 0;
}
int Search_Bin(SSTable ST, int key){
int begin = 1,last = ST.length;
while(begin<=last){
int mid = (begin+last)/2;
if(key==ST.R[mid].key){
return mid;
}else if(key<ST.R[mid].key){
last = mid-1;
}else if(key>ST.R[mid].key){
begin = mid+1;
}
}
return -1;
}
*/
/*
* #include<stdio.h>
#include<stdlib.h>
int main(void){
int i,n,target,index,flag=0;
int arr[100];
scanf("%d",&n);
for(i=1;i<=n;i++){
scanf("%d",&arr[i]);
}
scanf("%d",&target);
for(i=1;i<=n;i++){
if(arr[i]==target){
flag = 0;
index = i;
break;
}else{
flag = 1;
}
}
if(flag==1){
printf("NOT FOUND");
}else{
printf("%d",index);
}
return 0;
}
* */
#include<stdio.h>
#include<stdlib.h>
typedef struct
{
int *R;
int length;
} SSTable;
void Init(SSTable *ST){
ST->length=0;
ST->R = (int *) malloc(sizeof(int)*100);
}
int Search_Bin(SSTable ST,int x);
int main(){
int x;
SSTable ST;
Init(&ST);
scanf("%d",&ST.length);
for(int i=1;i<=ST.length;i++){
scanf("%d",&ST.R[i]);
}
scanf("%d",&x);
int ret = Search_Bin(ST,x);
if(ret==-1){
printf("NOT FOUND");
}else{
printf("%d",ret);
}
return 0;
}
int Search_Bin(SSTable ST,int x){
int begin = 1,last = ST.length;
while(begin<=last){
int mid = (begin+last)/2;
if(x==ST.R[mid]){
return mid;
}else if(x<ST.R[mid]){
last = mid-1;
}else if(x>ST.R[mid]){
begin = mid+1;
}
}
return -1;
}