qsort包括在<stdlib.h>头文件里。此函数依据你给的比較条件进行高速排序,通过指针移动实现排序。
排序之后的结果仍然放在原数组中。使用qsort函数必须自己写一个比較函数。
函数原型:
void qsort ( void * base, size_t num, size_t size, int ( * comparator ) ( const void *, const void * ) );
使用方法以及參数说明:
Sorts the num elements of the array pointed by base, each element size bytes
long, using the comparator function to determine the order.
The sorting algorithm used by this function compares pairs of values by calling the specified comparator function with two pointers to elements
of the array.
The function does not return any value, but modifies the content of the array pointed by base reordering its elements to the newly sorted order.
base Pointer to the first element of the array to be sorted.(数组起始地址)
num Number of elements in the array pointed by base.(数组元素个数)
size Size in bytes of each element in the array.(每个元素的大小)
comparator Function that compares two elements.(函数指针。指向比較函数)
1、The function must accept two parameters that are pointers to elements, type-casted as void*. These parameters should be cast back to some data type and be compared.
2、The return value of this function should represent whether elem1 is considered less than, equal to, or greater than elem2 by returning, respectively, a negative value, zero or a positive value.
Return Value none (无返回值)
>>>1. 对整形数据进行排序:(从小到大)
int Num[1010]; qsort(Num, n, sizeof(int), cmp); int cmp(const void *a, const void *b)
{
return *(int *)a - *(int *)b;
}
从大到小:
int cmp(const void *a, const void *b)
{
return *(int *)b - *(int *)a;
}
>>>2. 对char數據進行排序:
char str[1010]; qsort(str, sizeof(str), sizeof(char), cmp); int cmp(const void *a, const void *b)
{
return *(int *)a - *(int *)b;
}
>>>3. 對double數據進行排序:
double Num[1010]; qsort(Num, n, sizeof(double), cmp); int cmp(const void *a, const void *b)
{
return *(double *)a > *(double *)b ? 1 : -1;
}
>>>4. 對結構體數據進行排序:
typedef struct Node_
{
int data;
int position;
}Node; Node Num[1010]; qsort(Node, n, sizeof(Node), cmp); int cmp(const void *a, const void *b)
{
Node *p1 = (Node *)a;
Node *p2 = (Node *)b;
if(p1->data != p2->data) return p1->data - p2->data;
else return p1->position - p2->position;
}
實例:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#define MAXN 1010
#define RST(N)memset(N, 0, sizeof(N))
using namespace std; typedef struct Node_
{
char name[MAXN];
int data;
int position;
}Node; Node N[MAXN]; int cmp(const void *a, const void *b) //先對data進行從大到小,position和name從小到大排序
{
Node *p1 = (Node *)a;
Node *p2 = (Node *)b;
if(p1->data != p2->data) return p2->data - p1->data;
else if(p1->position != p2->position) {
return p1->position - p2->position;
}else return strcmp(p1->name, p2->name);
} int main()
{
int n;
while(~scanf("%d", &n)) {
for(int i=0; i<n; i++) {
scanf("%s %d %d", N[i].name, &N[i].data);
N[i].position = i;
}
qsort(N, n, sizeof(Node), cmp);
printf("------------------------------------\n");
for(int i=0; i<n; i++) {
printf("%s %d %d\n", N[i].name, N[i].data, N[i].position);
}
}
return 0;
}