C++中自帶了一些排序函數,其中STL的sort();qsort()用的較多
sort:複雜度爲n*log2(n)
頭文件
#include <algorithm>
原型:
template
<
class
RandomAccessIterator>
void
sort
( RandomAccessIterator first, RandomAccessIterator last );
template
<
class
RandomAccessIterator,
class
Compare>
void
sort
( RandomAccessIterator first, RandomAccessIterator last, Compare comp );
bool compare(int a,int b)
{
return a<b; //升序排列,如果改爲return a>b,則爲降序
}
qsort:
原型:
void qsort(void *base, int nelem, unsigned int width, int ( * pfCompare)( const
void *, const void *));
參數分別是數組指針,元素個數,每個元素大小(sizeof),比較函數
比較函數自己定義,如 int compare(const void *a,const void *b) 。
若*a排在*b前,返回負值
*a排在*b前後都行,返回0
*a排在*b後面,返回正值
顯然,返回值並不依賴大小,還依賴排序的要求;
示例:
#include
#include
#include
using namespace std;
int compare(const void *a, const void *b)
{
int pca = *(int *)a;
int pcb = *(int *)b;
return (pca-pcb) ; //從小到大排序
//return (pcb-pca) ;//從大到小排序
}
int main()
{
int a[10] = {5, 6, 4, 3, 7, 0 ,8, 9, 2, 1};
qsort(a, 10, sizeof(int), compare);
for (int i = 0; i < 10; i++)
cout << a[i] << " " ;
return 0;
}