各種查詢方法程式碼
阿新 • • 發佈:2021-01-03
順序查詢
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <time.h> 4 5 #define MAX 100 6 7 struct element 8 { 9 int key; 10 }; 11 12 typedef struct element record; 13 record data[MAX]; 14 15 int seq_search(int key) 16 { 17 int pos; 18 19 pos = 0; 20 while(pos < MAX) 21 { 22 if(key == data[pos].key) 23 return pos; 24 pos++; 25 } 26 return -1; 27 } 28 29 int main() 30 { 31 int checked[300]; 32 int i,temp; 33 long temptime; 34 srand(time(&temptime)%60); 35 for(i = 0;i < 300;i++) 36 checked[i] = 0; 37 i = 0; 38 while(i != MAX) 39 { 40 temp = rand()%300; 41 if(checked[temp] == 0) 42 { 43 data[i].key = temp; 44 checked[temp] = 1; 45 i++; 46 } 47 } 48 while(1) 49 { 50 printf("\n請輸入查詢值(0-299) ==>"); 51 scanf("%d",&temp); 52 if(temp != -1) 53 { 54 i = seq_search(temp); 55 if(i != -1) 56 printf("找到查詢值:%d[%d]\n",temp,i); 57 else 58 printf("沒有找到查詢值:%d\n",temp); 59 } 60 else 61 exit(1); 62 } 63 64 return 0; 65 }