Professional Documents
Culture Documents
Binary Search (Bsearch Method) : Syntax
Binary Search (Bsearch Method) : Syntax
Syntax:
void *bsearch(const void *desired, const void *list, size_t nitems, size_t size,
int (*compare)(const void *, const void *))
Parameters:
desired -- This is the pointer to the object that serves as key for the search, type-casted as a void*.
list -- This is the pointer to the first object of the array where the search is performed, type-casted as a void*.
nitems -- This is the number of elements in the array pointed by base.
size -- This is the size in bytes of each element in the array.
compare -- This is the function that compares two elements.
Algorithm:
#include <stdio.h>
#include <stdlib.h> /* for bsearch */
int list[] = { 5, 20, 29, 32, 63 };
int cmpfunc(const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main ()
{
int *item;
int desired = 32;
/* using bsearch() to find value 32 in the array */
item = (int*) bsearch (&desired, list, 5, sizeof (int), cmpfunc);
if( item != NULL )
printf("%d is Found\n", desired);
else
printf("%d could not be found\n", desired);
}
return 0;
Data Type
Size
char
1 Byte
int
2 Byte(short) / 4 Byte(long)
long long
8 Byte
float
4 Byte (6)
double
8 Byte ()
long double
10 Byte ()
Parameters:
list -- This is the pointer to the first element of the array to be sorted.
#include <stdio.h>
#include <stdlib.h> /* for qsort */
int list[] = { 88, 56, 100, 2, 25 };
int cmpfunc (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main()
{
int n;
printf("Before sorting the list is: \n");
for( n = 0 ; n < 5; n++ )
printf("%d ", values[n]);
qsort(list, 5, sizeof(int), cmpfunc); /* quickly sorting the list*/
printf("\nAfter sorting the list is: \n");
for( n = 0 ; n < 5; n++ )
printf("%d ", values[n]);
}
return(0);
Is It Prime? Algortihm
int IsPrime(unsigned int number)
{
if (number <= 1)
return 0; // zero and one are not prime
unsigned int i;
for (i = 2; i * i <= number; i++) {
if (number % i == 0)
return 0;
}
}
return 1;
as