c语言qsort的使用

目的

基于快速排序对数组进行排序,数组元素可以是结构体。

前提

qsort属于内置函数,需要包含头文件 stdlib.h

函数原型

void qsort( void *ptr, size_t count, size_t size,int (*comp)(const void *, const void *) );
/**
void *ptr:空指针, 指向需要排序的数组
size_t count:数组元素个数,size_t在32位机器上unsigned int(4byte),64位机器上unsigned long(8byte)
size:数组元素的字节数大小,通常用sizeof()来计算,平台不同,同一类型的变量占据的字节数可能不用,增强可移植性
int (*comp)(const void *, const void *) : 函数指针,将函数名作为参数,该函数的形参的类型均为const void *,函数外表是一样的,内容却有所不同,返回值类型相同
**/

用户自定义函数

指明具体的比较对象

int cmp(const void *a, const void *b); // 自定义函数内容,若果a值大于b值,返回1,
{
  /**
在函数内部将const void* 转换成实际的类型;
**/
//默认升序写法
if ( *(MyType*)a <  *(MyType*)b ) 
    return -1;
if ( *(MyType*)a == *(MyType*)b ) 
    return 0;
if ( *(MyType*)a >  *(MyType*)b ) 
    return 1;
}

结构体排序

struct Node { 
  int x; 
}s[100];
int cmp(const void *a, const void *b); 
{

if ( (*(Node*)a)->x <  (*(Node*)b)->x ) 
    return -1;
if ( (*(Node*)a)->x == (*(Node*)b)->x ) 
    return 0;
if ( (*(Node*)a)->x >  (*(Node*)b)->x ) 
    return 1;
}

多级排序

用于结构体内有多个成员时,当x相同时,比较y,以此类推即可。

struct Node { 
  int x; 
  int y;
  int z; 
}s[100];
int cmp(const void *a, const void *b); 
{

}

调用

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
 
int compare_ints(const void* a, const void* b)
{
    int arg1 = *(const int*)a;
    int arg2 = *(const int*)b;
 
    if (arg1 < arg2) return -1;
    if (arg1 > arg2) return 1;
    return 0;
 
    // return (arg1 > arg2) - (arg1 < arg2); // possible shortcut
    // return arg1 - arg2; // erroneous shortcut (fails if INT_MIN is present)
}
 
int main(void)
{
    int ints[] = { -2, 99, 0, -743, 2, INT_MIN, 4 };
    int size = sizeof ints / sizeof *ints;
 
    qsort(ints, size, sizeof(int), compare_ints);
 
    for (int i = 0; i < size; i++) {
        printf("%d ", ints[i]);
    }
 
    printf("\n");
}

猜你喜欢

转载自www.cnblogs.com/vito_wang/p/12499582.html