6-9 在數組中查找指定元素 (15分)
本題要求實現一個在數組中查找指定元素的簡單函數。
函數接口定義:
int search( int list[], int n, int x );
其中list[]
是用戶傳入的數組;n
(≥0)是list[]
中元素的個數;x
是待查找的元素。如果找到
則函數search
返回相應元素的最小下標(下標從0開始),否則返回−1。
裁判測試程序樣例:
#include <stdio.h> #define MAXN 10 int search( int list[], int n, int x ); int main() { int i, index, n, x; int a[MAXN]; scanf("%d", &n); for( i = 0; i < n; i++ ) scanf("%d", &a[i]); scanf("%d", &x); index = search( a, n, x ); if( index != -1 ) printf("index = %d\n", index); else printf("Not found\n"); return 0; } /* 你的代碼將被嵌在這里 */
輸入樣例1:
5
1 2 2 5 4
2
輸出樣例1:
index = 1
輸入樣例2:
5 1 2 2 5 4 0
輸出樣例2:
Not found
int search( int list[], int n, int x )
{
int i;
for(i=0;i<n;i++)
{
if(list[i]==x)
{
return i;
}
}
return -1;
}