資料結構C語言>數組>一維數組的遍曆 空間換取時間

來源:互聯網
上載者:User

首先看代碼1:

 

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 int main(int argc, char *argv[])
 5 {
 6   int score[10]={76,85,90,67,59,79,82,95,91,65};
 7   int num;
 8   int grade;
 9   int i;
10   
11   num=-1;
12   printf("用學產生績查詢學號");
13   printf("請輸入學產生績(0到100)。==> ");
14   scanf("%d",&grade);
15   for(i=0;i<10;i++)
16   {
17     if(score[i]==grade)
18     {
19       num=i;
20       break;
21     }
22   }
23   if(num !=- 1)
24   {
25     printf("學生學號是:%d\n",num);     
26   }
27   else
28   {
29       printf("沒有此成績的學生\n");
30   }
31   
32   system("PAUSE");    
33   return 0;
34 }
35 

 

 

很明顯,最壞的情況,什麼也查不到,但整個數組遍曆了。

 

看代碼2:

 

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 int main(int argc, char *argv[])
 5 {
 6   int score[10]={76,85,90,67,59,79,82,95,91,65};
 7   int pointer[101];
 8   int index;
 9   int grade;
10   int i;
11   
12   /*第一部分:建立指標數組*/
13   for(i=0; i<=101; i++)
14   {
15     pointer[i] = -1;       
16   }
17   for(i=0; i<10; i++)
18   {
19     index=score[i];
20     pointer[index]=i;       
21   }
22   /*第二部分:查詢學生學號*/
23   while(1)
24   {
25     printf("請輸入學產生績(0到100).==>");
26     scanf("%d",&grade);
27     if(grade != -1)
28     {
29       index = pointer[grade];
30       if(index != -1)
31       {printf("學生學號是:%d\n",index);}
32       else
33       {printf("沒有此成績的學生\n");}       
34     }
35     else
36     {exit(1);}      
37   }
38   
39   
40   system("PAUSE");    
41   return 0;
42 }
43 

 

除了第一次查詢要建立pointer數組外,以後每次查詢都可以固定時間內找到。當然,此程式的前提是,每個成績只出現一次。那麼出現多次呢?我也沒想好。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.