前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >在stm32开发可以调用c标准库的排序和查找 qsort bsearch

在stm32开发可以调用c标准库的排序和查找 qsort bsearch

作者头像
用户4645519
修改2020-09-07 11:36:15
6610
修改2020-09-07 11:36:15
举报
文章被收录于专栏:嵌入式学习嵌入式学习

在嵌入式开发中,可以使用c标准库自带的库函数,而不用自己去早轮子,qsort 和bsearch就是其中的两个比较好用的

二分法查找,前提是已经排序好的数据。下面的代码, 如果数据为排序,则要进行排序后,再查找。

代码语言:javascript
复制
/* bsearch example */
#include <stdio.h>      /* printf */
#include <stdlib.h>     /* qsort, bsearch, NULL */

int compareints (const void *a, const void *b)
{
    return ( *(int *)a - * (int *)b );
}

int values[] = { 50, 20, 60, 40, 10, 30 };

int main ()
{
    int *pItem;
    int key = 45;
    qsort (values, 6, sizeof (int), compareints);
    pItem = (int *) bsearch (&key, values, 6, sizeof (int), compareints);
    if (pItem != NULL)
        printf ("%d is in the array.\n", *pItem);
    else
        printf ("%d is not in the array.\n", key);
    return 0;
}

快速排序

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>

int values[] = { 88, 56, 100, 2, 25 };

int cmpfunc (const void *a, const void *b)
{
    return ( *(int *)a - * (int *)b );  //升序
    //return ( *(int *)a - * (int *)b );  //降序
}

int main()
{
    int n;

    printf("排序之前的列表:\n");
    for ( n = 0 ; n < 5; n++ )
    {
        printf("%d ", values[n]);
    }

    qsort(values, 5, sizeof(int), cmpfunc);

    printf("\n排序之后的列表:\n");
    for ( n = 0 ; n < 5; n++ )
    {
        printf("%d ", values[n]);
    }

    return (0);
}

比较函数需要特别注意~~~~

Pointer to a function that compares two elements. This function is called repeatedly by qsort to compare two elements. It shall follow the following prototype:

代码语言:javascript
复制
int compar (const void* p1, const void* p2);

Taking two pointers as arguments (both converted to const void*). The function defines the order of the elements by returning (in a stable and transitive manner):

return value

meaning

<0

The element pointed to by p1 goes before the element pointed to by p2

0

The element pointed to by p1 is equivalent to the element pointed to by p2

>0

The element pointed to by p1 goes after the element pointed to by p2

For types that can be compared using regular relational operators, a general compar function may look like:

代码语言:javascript
复制
int compareMyType (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;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-08-31 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档