返回列表 發帖

排序 - array

本帖最後由 tonyh 於 2022-12-22 19:31 編輯

int n[]={5,7,3,9,8,1,2};

練習以各種可能的方式,針對 array 做遞增與遞減排序。
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int n[]= {5,7,3,9,8,1,2};

  4. bool compare(int a, int b)
  5. {
  6.     return a>b;
  7. }

  8. void show()
  9. {
  10.     for(int i: n)
  11.         cout<<i<<" ";
  12.     cout<<endl;
  13. }

  14. int main()
  15. {
  16.     int len=sizeof(n)/sizeof(n[0]);

  17.     show();

  18.     //遞增
  19.     sort(n, n+len);
  20.     //sort(begin(n),end(n));
  21.     show();

  22.     //遞減
  23.     //sort(rbegin(n),rend(n));
  24.     sort(n, n+len, compare);
  25.     //sort(n, n+len, greater<int>());
  26.     show();

  27.     return 0;
  28. }
複製代碼
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int n[]= {5,7,3,9,8,1,2};

  4. bool compare(int a, int b)
  5. {
  6.     return a>b;    //遞減
  7. }

  8. int main()
  9. {
  10.     int len=sizeof(n)/sizeof(int);
  11.     //cout<<len<<endl;

  12.     for(int i: n)
  13.         cout<<i<<" ";
  14.     cout<<endl;

  15.     /*for(int i=0; i<len; i++)
  16.         cout<<n[i]<<" ";
  17.     cout<<endl;*/

  18.     cout<<"-----------------"<<endl;

  19.     //遞增
  20.     //sort(n,n+len);
  21.     sort(begin(n),end(n));

  22.     for(int i: n)
  23.         cout<<i<<" ";
  24.     cout<<endl;

  25.     cout<<"-----------------"<<endl;

  26.     //遞減
  27.     //sort(rbegin(n),rend(n));
  28.     //sort(begin(n),end(n),greater<int>());  //less<int>()
  29.     sort(begin(n),end(n),compare);

  30.     for(int i: n)
  31.         cout<<i<<" ";
  32.     cout<<endl;

  33.     return 0;
  34. }
複製代碼

返回列表