在實際開發中,經常需要查詢數組中的元素。例如,學校為每位同學分配了一個唯一的編號,現在有一個數組,保存了實驗班所有同學的編號信息,如果有家長想知道他的孩子是否進入了實驗班,只要提供孩子的編號就可以,如果編號和數組中的某個元素相等,就進入了實驗班,否則就沒進入。
不幸的是,C語言標准庫沒有提供與數組查詢相關的函數,所以我們只能自己編寫代碼。
對無序數組的查詢
所謂無序數組,就是數組元素的排列沒有規律。無序數組元素查詢的思路也很簡單,就是用循環遍歷數組中的每個元素,把要查詢的值挨個比較一遍。請看下面的代碼:
- #include <stdio.h>
- #include <stdlib.h>
- int main(){
- int nums[10] = {1, 10, 6, 296, 177, 23, 0, 100, 34, 999};
- int i, num, subscript = -1;
- printf("Please input an integer: ");
- scanf("%d", &num);
- for(i=0; i<10; i++){
- if(nums[i] == num){
- subscript = i;
- break;
- }
- }
- if(subscript<0){
- printf("%d isn't in the array.\n", num);
- }else{
- printf("%d is in the array, and it's subscript is %d.\n", num, subscript);
- }
- system("pause");
- return 0;
- }
運行結果:
Please input an integer: 100
100 is in the array, and it's subscript is 7.
或者
Please input an integer: 28
28 isn't in the array.
這段代碼的作用是讓用戶輸入一個數字,判斷該數字是否在數組中,如果在,就打印出下標。
第10~15行代碼是關鍵,它會遍歷數組中的每個元素,和用戶輸入的數字進行比較,如果相等就獲取它的下標並跳出循環。
注意:數組下標的取值范圍是非負數,當 subscript >= 0 時,該數字在數組中,當 subscript < 0 時,該數字不在數組中,所以在定義 subscript 變量時,必須將其初始化為一個負數。
對有序數組的查詢
查詢無序數組需要遍歷數組中的所有元素,而查詢有序數組只需要遍歷其中一部分元素。例如有一個長度為10的整型數組,它所包含的元素按照從小到大的順序(升序)排列,假設比較到第4個元素時發現它的值大於輸入的數字,那么剩下的5個元素就沒必要再比較了,肯定也大於輸入的數字,這樣就減少了循環的次數,提高了執行效率。
請看下面的代碼:
- #include <stdio.h>
- #include <stdlib.h>
- int main(){
- int nums[10] = {0, 1, 6, 10, 23, 34, 100, 177, 296, 999};
- int i, num, subscript = -1;
- printf("Please input an integer: ");
- scanf("%d", &num);
- for(i=0; i<10; i++){
- if(nums[i] >= num){
- if(nums[i] == num){
- subscript = i;
- }
- break;
- }
- }
- if(subscript<0){
- printf("%d isn't in the array.\n", num);
- }else{
- printf("%d is in the array, and it's subscript is %d.\n", num, subscript);
- }
- system("pause");
- return 0;
- }
注意第11行代碼,只有當 nums[i] >= num 成立時才進行處理,否則繼續循環。nums[i] >= num 有兩重含義:
- 如果 nums[i] == num,則 num 在數組中,那么就需要給 subscript 賦值,記錄當前元素的下標;
- 如果 nums[i] > num,則 nums 不在數組中。
無論哪種情況,都沒有必要再繼續循環下去了,所以一旦滿足 nums[i] >= num,就應該使用 break 跳出循環。