Last active
July 21, 2022 17:14
-
-
Save viraatmaurya/4bd50e9f16f4a30ba75acb0dfaff9285 to your computer and use it in GitHub Desktop.
Linear search for integers using pointer.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
int compare(void *a, void *b) | |
{ | |
int * ap = a; | |
int * bp = b; | |
return *ap - *bp; | |
} | |
void * lsearch(void *key, void *base, int n, int elemsize) | |
{ | |
for (int i = 0; i < n; i++) | |
{ | |
void *elemaddress = (char*) base + i * elemsize; | |
if (compare(key, elemaddress) == 0) | |
{ | |
return elemaddress; | |
} | |
} | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
int array[] = {1,2,3,4,5,6,7,8,9,10}; | |
int size = sizeof(array)/sizeof(array[0]); | |
int key = 7; | |
int* result = lsearch(&key, &array, size, sizeof(array[0])); | |
printf("Index for Kay match is :%d\n", *result); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment