qsort的用法

C/C++中有一个快速排序的标准库函数qsort,在stdlib.h中声明,其原型为:

void qsort(void *base, int nelem, unsigned int width, int (* pfCompare)(const void *,const void *));

其中base为待排序的数组,nelem为数组元素个数,width为数组每个元素的大小(以字节为单位),pfCompare为函数指针,指向一个“比较函数”,需要根据自己的需求编写。

“比较函数”原型:

int 函数名(const void * elem1, const void * elem2);

elem1和elem2是两个待比较的元素

1)如果*elem1应该排在*elem2前面,则函数返回值为负整数

2)如果*elem1和*elem2哪个排在前面都行,则函数返回值为0

3)如果*elem1应该排在elem2后面,则函数返回值为正整数

下面是几个例子:

1.按个位数从小到大排序

#include 
#include 
using namespace std;
#define NUM 5
int MyCompare(const void * elem1,const void * elem2)
{
    int * p1 = (int *) elem1;
    int * p2 = (int *) elem2;
    return *p1%10-*p2%10;
}
int main()
{
    int arr[NUM]={1,55,7,192,32};
    qsort(arr,NUM,sizeof(int),MyCompare);
    for(int i=0;i

2.从大到小排序

#include 
#include 
using namespace std;
#define NUM 5
int MyCompare(const void * elem1, const void * elem2)
{
    int * p1 = (int *)elem1;
    int * p2 = (int *)elem2;
    return *p2-*p1;
}
int main()
{
    int arr[NUM]={5,88,2,13,71};
    qsort(arr,NUM,sizeof(int), MyCompare);
    for(int i=0;i

3.给结构体student排序

#include 
#include 
#include 
using namespace std;
#define NUM 5
struct Student{
    unsigned ID;
    char szName[20];
    float fGPA;
};
Student MyClass[NUM]={
    {1234,"Tom",3.78},
    {1345,"Sam",2.12},
    {1235,"Bob",4.77},
    {1456,"Echo",1.34},
    {1578,"Amy",3.04},
};

int IDCompare(const void * elem1,const void * elem2)
{
    Student * stu1 = (Student*)elem1;
    Student * stu2 = (Student*)elem2;
    return (*stu1).ID-(*stu2).ID;
}
int NameCompare(const void * elem1, const void * elem2)
{
    Student * stu1 = (Student*)elem1;
    Student * stu2 = (Student*)elem2;
    return strcmp(stu1->szName,stu2->szName);
}
int main()
{
    qsort(MyClass,NUM,sizeof(Student),IDCompare);
    for(int i=0;i

4.自定制qsort

内部采用冒泡排序

#include 
#include 
using namespace std;
#define NUM 5
int MyCompare(const void * elem1, const void * elem2)
{
    int * p1 = (int *)elem1;
    int * p2 = (int *)elem2;
    return *p1-*p2;
}
void Myqsort(void * arr,int num,int size,int (*pfcompare)(const void * ele1, const void * ele2))
{
    char * a = (char *)arr;
    //冒泡排序
    for(int i=num-1;i>0;i--){
        for(int j=0;j0)
                for(int k=0;k

 

你可能感兴趣的:(C语言,C++,算法基础习题)