C语言自带的比较函数与排序函数——fmax、qsort

比较函数

fmax() &&fmin()

在头文件<math.h>中定义

float fmaxf( float x, float y );

(1)

(自C99)

double fmax( double x, double y );

(2)

(自C99)

long double fmaxl( long double x, long double y );

(3)

(自 C99)

Defined in header <tgmath.h>

#define fmax( x, y )

(4)

(自C99)

返回值

如果成功,则fmax()/fmin()返回两个浮点值中较大/小的一个。

//数组中连续1的最大个数
int findMaxConsecutiveOnes(int* nums, int numsSize) {
    int maxCount = 0, count = 0;
    for (int i = 0; i < numsSize; i++) {
        if (nums[i] == 1) {
            count++;
        } else {
            maxCount = fmax(maxCount, count);
            count = 0;
        }
    }
    maxCount = fmax(maxCount, count);
    return maxCount;
}

fdim()

double fdim(double x,double y) ;
float fdimf (float x,float y) ;
long double fdiml (long double x, long double y) ;
/*    使用fdim函数判断传入的第一个参数(x)是否大于第二个参数(y)
      如果x > y 则返回两者的差值( x - y ) 
      如果 x < y 则返回 0 
*/
包含头文件:include<math.h>

#include <stdio.h>  
#include <math.h>  
     
int main ()
{
  printf ("fdim (2.0, 1.0) = %f\n", fdim(2.0,1.0)); //1.000000
  printf ("fdim (1.0, 2.0) = %f\n", fdim(1.0,2.0)); //0.000000
  printf ("fdim (-2.0, -1.0) = %f\n", fdim(-2.0,-1.0)); // 0.000000
  printf ("fdim (-1.0, -2.0) = %f\n", fdim(-1.0,-2.0));  //1.000000
  return 0;
}

qsort()函数

void qsort( void *base, size t m, size t width, 
    int(_cdecl *compare )(const void *eleml, const void *elem2 ));

/*
base  : 待排序的数组
num   : 数组元素的个数
width : 单个元素的大小
compare :实现一个比较函数
*/
compare(const void *p1, const void *p2 ){
 //首先看排序函数的参数 排序函数的参数类型 一定是const void*
    //const—可以使在函数运行的过程中 原数组的值不被改变
    //void—是为了提升函数普适性,强制规定函数参数为void*
}

//如果compare返回值<0,那么p1所指向元素会被排在p2所指向元素的前面 ;
//等于0,那么p1所指向元素与p2所指向元素的顺序不确定 
// > 0,那么p1所指向元素会被排在p2所指向元素的后面 
 int compare (const void * a, const void * b)
 {
   if ( *(MyType*)a <  *(MyType*)b ) return -1; 
   if ( *(MyType*)a == *(MyType*)b ) return 0;
   if ( *(MyType*)a >  *(MyType*)b ) return 1; 
 }
//注意:你要将MyType换成实际数组元素的类型。 
or
int compare (const void * a, const void * b){
    return ( *(MyType*)a - *(MyType*)b );
}

 //题目:给你一个非空数组,返回此数组中 第三大的数 。如果不存在,则返回数组中最大的数。


int cmp(const void *a,const void *b){
    return *(int*)a < *(int*)b;
}
int thirdMax(int* nums, int numsSize){
    //从大到小排序
    qsort(nums,numsSize,sizeof(nums[0]),cmp);
    int diff = 0;
    for(int i = 1;i < numsSize ;i++){
        if(nums[i] != nums[i-1] && ++diff == 2){
            return nums[i];
        }
    }
    return nums[0];
}

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值