bsearch function program in c language
bsearch function in c used to perform the search in the array and array will be sorted by the ascending order.
A pointer will be used to sorted the array and the base point to the initial element for the given array and the key pointed to the object that containing the value that going to be sorted with the comparison function.
Return value for the bsearch program:-
If search goes successful, bsearch() returns a pointer to an identical element of the array. If two or more elements are equal, the element pointed to that it is not specified.
If search goes unsuccessful finding the key, bsearch() returns NULL.
#include<stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #define NOSTRING 5 #define SIZE 26 int string_compare(void const *, void const *); int main(void) { int i; char strings[NOSTRING][SIZE]; char search_str[SIZE]; char *status; /* read strings from the user */ printf("User, write in %d character strings...\n", NOSTRING); for (i= 0; i < NOSTRINGS; i++) fgets(strings[i], SIZE, stdin); printf("\n\n"); /* display array of unsorted strings */ printf("Before Sorting:\n"); for (i = 0; i < NOSTRING; i++) fputs(strings[i], stdout); /* sort the array */ qsort(strings, NOSTRING, SIZE, string_compare); printf("\n"); /* array of sorted strings */ printf("After Sorting:\n"); for (i = 0; i < NOSTRING; i++) printf(strings[i], stdout); printf("\n\n"); /* read the string to be searched for */ printf("programer write about string you wish to search for...\n"); fgets(search_str, SIZE, stdin); printf("\n"); /* calling bsearch() to locate given string in the array */ status = bsearch(search_str, strings, NOSTRINGS, SIZE, string_compare); /* verify if given value is found */ assert(status != NULL); printf("your desired string is found!\n"); return 0; } int string_compare(void const *str1, void const *str2) { return strcmp((char *)str1, (char *)str2); }
OUTPUT : -
bsearch function program in c programming language |
0 comments:
Post a Comment