資料結構與演算法分析——C語言描述

來源:互聯網
上載者:User

標籤:

P1.1 選擇問題,選擇出第K大的數,並畫出N為不同值的已耗用時間,K=N/2

畢業兩年半,重寫排序,感覺良好。代碼使用冒泡排序,庫函數clock計算大致已耗用時間。

 1 // P1_1.cpp : Defines the entry point for the console application. 2 // 3  4 #include "stdafx.h" 5 #include <malloc.h> 6 #include <stdlib.h> 7  #include <time.h>  8  9 void swap(int& a,int& b);10 11 int main(int argc, char* argv[])12 {13 14     int N = 40000;15     int k = N/2;16     int i,j;17 18     //動態數組19     int *dynArr = (int *)malloc(N * sizeof(int));20     //產生隨機數組21      srand((unsigned) time(NULL));22      //printf("%d%c", rand(),‘\t‘);23      for(i=0; i<N;i++)24      {25          dynArr[i] = rand()%100;26          //printf("%d%c",dynArr[i],‘\t‘);27      }28 29 30     int beginTime = clock();//計時開始31 32     //冒泡排序33     int temp = 0;34     for(i=0;i<N;i++)35         for(j=0;j<N;j++)36         {37             if(dynArr[i]>dynArr[j]){    //左>右,交換38                 swap(dynArr[i],dynArr[j]);39             }    40         }//第一層結束,最大數在最右41 42     int endTime = clock();//計時結束43     int runningTime = endTime - beginTime;//算出來的單位是毫秒44 45 46 47     for(i=0; i<N;i++){48     //     dynArr[i] = rand()%100;49          //printf("%d%c",dynArr[i],‘\t‘);50      }51     52     char str1[] = "個數中第k大的數:";53     char str2[] = "已耗用時間(毫秒):";54     printf("\n%d%s%d\t",N,str1,dynArr[k]);55 printf("\n%s%d\n",str2,runningTime);56 57 58     return 0;59 }60 61 void swap(int& left,int& right){62     int temp;63     temp = left;64     left = right;65     right = temp;66 }

更改N值,來測試不同樣本值的已耗用時間。

假如資料是學生的一個科目的考試成績,百分制。N表示學生的個數。

N Time(ms)
00
501
1005
50049
1000101
5000272

N(萬)Time(ms)
1281
21109
32506
44384
56764
69747
713296
817421
922078
1027307

用這個網站繪製曲線圖:

感覺就是個遞增。其實這是假象...再看這兩個小圖:

             

人數是普通的遞增,但是時間可不是遞增,時間花費是迅速上升的。

資料結構與演算法分析——C語言描述

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.