返回列表 發帖

[隨堂測驗] 排序 (二)

產生10個範圍介於1~20之不重複隨機亂數, 並利用選擇排序法將它們由小而大排列出來.



本帖隱藏的內容需要回復才可以瀏覽

  1. #include<iostream>
  2. #include<ctime>
  3. using namespace std;
  4. int main()
  5. {
  6. srand(time(NULL));
  7. int t,a[10];
  8. for(int v=0;v<=9;v++)
  9. {
  10.     a[v]=rand()%20+1;
  11.     for(int o=0;o<v;o++)
  12.     {
  13.         if(a[v]==a[o])
  14.         {
  15.             v--;
  16.             break;
  17.         }
  18.     }
  19. }
  20. cout<<"排序前:";
  21. for(int v=0;v<10;v++)
  22.     cout<<a[v]<<" ";
  23. cout<<endl;
  24. for(int b=0;b<=9;b++)
  25. {
  26.     for(int c=b+1;c<=9;c++)
  27.     if(a[b]>a[c])
  28.     {
  29.        t=a[b] ;
  30.        a[b]=a[c];
  31.        a[c]=t;
  32.     }
  33. }
  34. cout<<"排序後:";
  35. for(int v=0;v<10;v++)
  36.     cout<<a[v]<<" ";
  37.     return 0;
  38. }
複製代碼

TOP

返回列表