sort 函数是一个极好的排序函数,因为其运行速度块,占用内存少,排序也省力,深受程序员们的喜爱,具体用法这里就不再多介绍了,今天主要强调以下几点快排:
1.从大到小快排:
#include <iostream>
#include <algorithm>
using namespace std;
int function(int m,int n){return m > n;
}
int main(){int n;cin >> n;int a[n];for (int i = 1;i<=n;i++){cin >> a[i];}sort(a+1,a+n+1, function);for (int i = 1;i<=n;i++){cout << a[i] << " ";}return 0;
}
2. 从小到大快排
这种方法可以用默认快排或者是用一个函数来辅助:
#include <iostream>
#include <algorithm>
using namespace std;
int function(int m,int n){return m < n;
}
int main(){int n;cin >> n;int a[n];for (int i = 1;i<=n;i++){cin >> a[i];}sort(a+1,a+n+1, function);for (int i = 1;i<=n;i++){cout << a[i] << " ";}return 0;
}
(用一个副函数来辅助)
#include <iostream>
#include <algorithm>
using namespace std;int main(){int n;cin >> n;int a[n];for (int i = 1;i<=n;i++){cin >> a[i];}sort(a+1,a+n+1);for (int i = 1;i<=n;i++){cout << a[i] << " ";}return 0;
}
(默认快排)
3. 快速交换(从后往前)
#include <iostream>
#include <algorithm>
using namespace std;int function(int m,int n){return m = n;
}
int main(){int n;cin >> n;int a[n];for (int i = 1;i<=n;i++){cin >> a[i];}sort(a+1,a+n+1, function);for (int i = 1;i<=n;i++){cout << a[i] << " ";}return 0;
}
如有不对,还请大佬们指出!!