C language using the qsort

purpose

Based on Quick Sort to sort the array, the array elements can be a structure.

premise

qsort belonging built-in functions, it is necessary to include the header stdlib.h

Function prototype

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 *,函数外表是一样的,内容却有所不同,返回值类型相同
**/

User-defined functions

Specify the specific comparison object

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;
}

Sorting structure

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;
}

Multi-level sorting

When the body structure for a plurality of members, when x is the same, comparison y, and so can.

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

}

transfer

#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");
}

Guess you like

Origin www.cnblogs.com/vito_wang/p/12499582.html