第二周項目3 - 體驗複雜度

來源:互聯網
上載者:User
問題及代碼:
//選擇排序  #include <stdio.h>  #include <time.h>  #include <stdlib.h>  #define MAXNUM 100000  void selectsort(int a[], int n)  {          int i, j, k, tmp;          for(i = 0; i < n-1; i++)          {                  k = i;                  for(j = i+1; j < n; j++)                  {                          if(a[j] < a[k])                                  k = j;                  }                  if(k != j)                  {                          tmp = a[i];                          a[i] = a[k];                          a[k] = tmp;                  }          }  }    int main()  {      int x[MAXNUM];      int n = 0;      double t1,t2;      FILE *fp;      fp = fopen("numbers.txt", "r");      if(fp==NULL)      {          printf("開啟檔案錯。請下載檔案,並將之複製到與來源程式檔案同一檔案夾下。\n");          exit(1);      }      while(fscanf(fp, "%d", &x[n])!=EOF)          n++;      printf("資料量:%d, 開始排序....", n);      t1=time(0);      selectsort(x, n);      t2=time(0);      printf("用時 %d 秒!", (int)(t2-t1));      fclose(fp);      return 0;  }  
//快速排序  #include <stdio.h>  #include <time.h>  #include <stdlib.h>  #define MAXNUM 100000  void quicksort(int data[],int first,int last)  {      int i, j, t, base;      if (first>last)          return;      base=data[first];      i=first;      j=last;      while(i!=j)      {          while(data[j]>=base && i<j)              j--;          while(data[i]<=base && i<j)              i++;          /*交換兩個數*/          if(i<j)          {              t=data[i];              data[i]=data[j];              data[j]=t;          }      }      data[first]=data[i];      data[i]=base;      quicksort(data,first,i-1);      quicksort(data,i+1,last);  }    int main()  {      int x[MAXNUM];      int n = 0;      double t1,t2;      FILE *fp;      fp = fopen("numbers.txt", "r");      if(fp==NULL)      {          printf("開啟檔案錯。請下載檔案,並將之複製到與來源程式檔案同一檔案夾下。\n");          exit(1);      }      while(fscanf(fp, "%d", &x[n])!=EOF)          n++;      printf("資料量:%d, 開始排序....", n);      t1=time(0);      quicksort(x, 0, n-1);      t2=time(0);      printf("用時 %d 秒!", (int)(t2-t1));      fclose(fp);      return 0;  }  

運行結果:

選擇排序 快速排序

知識點總結:在不同的時候用不同的演算法可以有效提升效率 學習心得:感受到了兩種演算法在已耗用時間上的差異

聯繫我們

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