C語言數組元素的查詢


對無序數組的查詢

所謂無序數組,就是數組元素的排列沒有規律。無序數組元素查詢的思路也很簡單,就是用循環遍歷數組中的每個元素,把要查詢的值挨個比較一遍。請看下面的代碼:

 1 #include <stdio.h>
 2 int main(){
 3     int nums[10] = {1, 10, 6, 296, 177, 23, 0, 100, 34, 999};
 4     int i, num, thisindex = -1;
 5    
 6     printf("Input an integer: ");
 7     scanf("%d", &num);
 8     for(i=0; i<10; i++){
 9         if(nums[i] == num){
10             thisindex = i;
11             break;
12         }
13     }
14     if(thisindex < 0){
15         printf("%d isn't  in the array.\n", num);
16     }else{
17         printf("%d is  in the array, it's index is %d.\n", num, thisindex);
18     }
19 
20     return 0;
21 }

運行結果:

Input an integer: 100↙
100 is  in the array, it's index is 7.

或者

Input an integer: 28↙
28 isn't  in the array.

這段代碼的作用是讓用戶輸入一個數字,判斷該數字是否在數組中,如果在,就打印出下標。

第10~15行代碼是關鍵,它會遍歷數組中的每個元素,和用戶輸入的數字進行比較,如果相等就獲取它的下標並跳出循環。

注意:數組下標的取值范圍是非負數,當 thisindex >= 0 時,該數字在數組中,當 thisindex < 0 時,該數字不在數組中,所以在定義 thisindex 變量時,必須將其初始化為一個負數。

 

對有序數組的查詢

查詢無序數組需要遍歷數組中的所有元素,而查詢有序數組只需要遍歷其中一部分元素。例如有一個長度為 10 的整型數組,它所包含的元素按照從小到大的順序(升序)排列,假設比較到第 4 個元素時發現它的值大於輸入的數字,那么剩下的 5 個元素就沒必要再比較了,肯定也大於輸入的數字,這樣就減少了循環的次數,提高了執行效率。

 1 #include <stdio.h>
 2 int main(){
 3     int nums[10] = {0, 1, 6, 10, 23, 34, 100, 177, 296, 999};
 4     int i, num, thisindex = -1;
 5    
 6     printf("Input an integer: ");
 7     scanf("%d", &num);
 8     for(i=0; i<10; i++){
 9         if(nums[i] == num){
10             thisindex = i;
11             break;
12         }else if(nums[i] > num){
13             break;
14         }
15     }
16     if(thisindex < 0){
17         printf("%d isn't  in the array.\n", num);
18     }else{
19         printf("%d is  in the array, it's index is %d.\n", num, thisindex);
20     }
21    
22     return 0;
23 }

與前面的代碼相比,這段代碼的改動很小,只增加了一個判斷語句,也就是 12~14 行。因為數組元素是升序排列的,所以當 nums[i] > num 時,i 后邊的元素也都大於 num 了,num 肯定不在數組中了,就沒有必要再繼續比較了,終止循環即可。

摘自http://c.biancheng.net/cpp/html/3151.html


免責聲明!

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



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