6-9 在數組中查找指定元素 (15分)


6-9 在數組中查找指定元素 (15分)
 

本題要求實現一個在數組中查找指定元素的簡單函數。

函數接口定義:

int search( int list[], int n, int x ); 
 

其中list[]是用戶傳入的數組;n0)是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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM