顺序查找
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef int ElemType;
typedef struct {
ElemType *elem;
int TableLen;
} SSTable;
void ST_Init(SSTable &ST, int len) {
ST.TableLen = len + 1;
ST.elem = (ElemType *) calloc(ST.TableLen, sizeof(ElemType));
int i;
srand(time(NULL));
for (int i = 1; i < ST.TableLen; ++i) {
ST.elem[i] = rand() % 100;
}
}
void ST_print(SSTable ST) {
for (int i = 1; i < ST.TableLen; ++i) {
printf("%d ", ST.elem[i]);
}
printf("\n");
}
int search_seq(SSTable ST, ElemType key) {
int i;
ST.elem[0]=key;
for (i = ST.TableLen-1; ST.elem[i]!=key; --i);
return i;
}
int main() {
SSTable ST;
ST_Init(ST, 10);
ST_print(ST);
ElemType key;
printf("please input key value to be search:\n");
scanf("%d", &key);
int pos = search_seq(ST, key);
printf("%d", pos);
return 0;
}
折半查找 — 有序顺序表
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef int ElemType;
typedef struct {
ElemType *elem;
int TableLen;
} SSTable;
void ST_Init(SSTable &ST, int len) {
ST.TableLen = len;
ST.elem = (ElemType *) calloc(ST.TableLen, sizeof(ElemType));
srand(time(NULL));
for (int i = 0; i < ST.TableLen; ++i) {
ST.elem[i] = rand() % 100;
}
}
void ST_print(SSTable ST) {
for (int i = 0; i < ST.TableLen; ++i) {
printf("%d ", ST.elem[i]);
}
printf("\n");
}
int BinarySearch(SSTable L, ElemType key) {
int low=0;
int high=L.TableLen-1;
int mid;
while (high>=low ){
mid=(high+low)/2;
if(key>L.elem[mid]){
low=mid+1;
} else if(key<L.elem[mid]){
high=mid-1;
} else if(key == L.elem[mid]){
return mid;
}
}
return -1;
}
int compare(const void *left, const void *right){
return *(int*)left-*(int*)right;
}
int main() {
SSTable ST;
ST_Init(ST, 10);
ST_print(ST);
qsort(ST.elem,ST.TableLen,sizeof (ElemType),compare);
ST_print(ST);
ElemType key;
printf("please input key value to be search:\n");
scanf("%d", &key);
int pos = BinarySearch(ST, key);
if(pos!=-1)
printf("find key %d\n", pos);
else
printf("not find\n");
return 0;
}