Built in function for searching sorted array in C

一个人想着一个人 提交于 2019-12-23 06:18:09

问题


Is there a built in function in C for searching an integer array that has been sorted?

I can easily implement it but it seems like such a common thing - would be weird if there is no library/built in C function.


回答1:


stdlib.h actually contains some sorting and searching functions. qsort will let you sort an array in place, and bsearch will perform binary search on a sorted array for you. You do have to provide a comparison function in both cases.




回答2:


There is bsearch() for binary search in sorted array https://www.tutorialspoint.com/c_standard_library/c_function_bsearch.htm

Example:

#include <stdio.h>
#include <stdlib.h>


int cmp_int(const void *pa, const void *pb) { 
    int a = *(int *)pa; 
    int b = *(int *)pb; 
    return (a > b) - (a < b); 
}

int values[] = { 5, 20, 29, 32, 63 };

int main () {
    int *item;
    int key = 32;

    /* using bsearch() to find value 32 in the array */
    item = (int*) bsearch (&key, values, 5, sizeof (int), cmpfunc);
    if( item != NULL ) {
        printf("Found item = %d\n", *item);
    } else {
        printf("Item = %d could not be found\n", *item);
    }

    return(0);
}

UPD Added proper comparer by @jonathan-leffler




回答3:


you need bsearch, this link will take you to the manual and an example provided in that manual. alternatively in a linux box you can type

man -a bsearch


来源:https://stackoverflow.com/questions/47320667/built-in-function-for-searching-sorted-array-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!