#include <stdio.h>
#include <string.h>
int nsearch(int array[], int size, int target);
int csearch(char array[], int size, char target);
int ssearch(char array[][10], int size, char *target);
int main(void)
{
int testa[10] = {3, 2, 8, 1, 9, 4, 7, 6, 5, 0};
char testb[10] = {'d', 't', '7', '#', 'c', 'q', 'n', ' ', 'o', 'v'};
char testc[10][10] = {"john", "mary", "tommy", "lily", "blue", "park", "tony", "sam", "bill", "bruse"};
int targeta = 7;
char targetb = 'q';
char *targetc = "sam";
printf("\n%d 的索引值是 %d\n\n", targeta, nsearch(testa, 10, targeta));
printf("\n%c 的索引值是 %d\n\n", targetb, csearch(testb, 10, targetb));
printf("\n%s 的索引值是 %d\n\n", targetc, ssearch(testc, 10, targetc));
return 0;
}
int nsearch(int array[], int size, int target)
{
int i;
for (i = 0; i < size; i++) {
if (target == array[i]) {
return i;
}
}
return -1;
}
int csearch(char array[], int size, char target)
{
int i;
for (i = 0; i < size; i++) {
if (target == array[i]) {
return i;
}
}
return -1;
}
int ssearch(char array[][10], int size, char *target)
{
int i;
for (i = 0; i < size; i++) {
if (!strcmp(array[i], target)) {
return i;
}
}
return -1;
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:lstest.c
功能:測試線性搜尋的函數
作者:張凱慶
時間:西元2010年7月 */編譯後執行,結果如下

程式碼說明,請繼續參考
沒有留言:
張貼留言