#include<stdio.h> #include<stdlib.h> #define EQ(a,b) ((a) == (b)) #define LT(a,b) ((a) < (b)) #define LE(a,b) ((a) <= (b)) typedef struct{ int key; int data; }SElemType; typedef struct{ SElemType *elem; int length; }SSTable; SSTable * create(int n) { SSTable *sst = (SSTable *)malloc(sizeof(SSTable)); int x; sst->elem = (SElemType*)malloc(sizeof(SElemType) * n); sst->length = n; for(int i = 1; i <= n ; i++) { scanf("%d",&x); sst->elem[i].data = x; sst->elem[i].key = i; } sst->elem[0].key = 0; sst->elem[0].key = 0; return sst; } int search(SSTable * st,int key) { int i; st->elem[0].key = key; for( i = st->length ;!EQ(st->elem[i].key,key);--i); return i; } int searchBin(SSTable * st,int key) { int low =1,high = st->length ; int mid=0; while(low <= high) { mid = (low + high)/2; if(EQ(key,st->elem[mid].key)) return mid; else if(LT(key,st->elem[mid].key)) high = mid -1; else low = mid +1; } return 0; } void main() { printf("Input number of element:\n"); int n; scanf("%d",&n); SSTable * sst = create(n); printf("the search table element are:\n"); for(int i = 1;i<=n;i++) { printf("%-5d",sst->elem[i].data); } printf("\nposition of key i is:\n"); printf("%d\n",search(sst,3)); printf("\nposition of key i (binary search) is:\n"); printf("%d\n",searchBin(sst,3)); system("pause"); }