本帖最後由 tonyh 於 2022-12-22 19:31 編輯
int n[]={5,7,3,9,8,1,2};
練習以各種可能的方式,針對 array 做遞增與遞減排序。- #include<bits/stdc++.h>
- using namespace std;
- int n[]= {5,7,3,9,8,1,2};
- bool compare(int a, int b)
- {
- return a>b;
- }
- void show()
- {
- for(int i: n)
- cout<<i<<" ";
- cout<<endl;
- }
- int main()
- {
- int len=sizeof(n)/sizeof(n[0]);
- show();
- //遞增
- sort(n, n+len);
- //sort(begin(n),end(n));
- show();
- //遞減
- //sort(rbegin(n),rend(n));
- sort(n, n+len, compare);
- //sort(n, n+len, greater<int>());
- show();
- return 0;
- }
複製代碼- #include<bits/stdc++.h>
- using namespace std;
- int n[]= {5,7,3,9,8,1,2};
- bool compare(int a, int b)
- {
- return a>b; //遞減
- }
- int main()
- {
- int len=sizeof(n)/sizeof(int);
- //cout<<len<<endl;
- for(int i: n)
- cout<<i<<" ";
- cout<<endl;
- /*for(int i=0; i<len; i++)
- cout<<n[i]<<" ";
- cout<<endl;*/
- cout<<"-----------------"<<endl;
- //遞增
- //sort(n,n+len);
- sort(begin(n),end(n));
- for(int i: n)
- cout<<i<<" ";
- cout<<endl;
- cout<<"-----------------"<<endl;
- //遞減
- //sort(rbegin(n),rend(n));
- //sort(begin(n),end(n),greater<int>()); //less<int>()
- sort(begin(n),end(n),compare);
- for(int i: n)
- cout<<i<<" ";
- cout<<endl;
- return 0;
- }
複製代碼 |