Skip to content

Instantly share code, notes, and snippets.

@sojohnnysaid
Created June 22, 2018 19:07
Show Gist options
  • Save sojohnnysaid/923afc6d47411dfff16b0e529955c977 to your computer and use it in GitHub Desktop.
Save sojohnnysaid/923afc6d47411dfff16b0e529955c977 to your computer and use it in GitHub Desktop.
another way of implementing linear search
#include <stdio.h>
int main(void)
{
// linear search
// given a value to find
// search each element in the array
// if found return the value/position
int haystack[] = {1,2,3,4,5,6};
int length = sizeof haystack/sizeof haystack[0];
int needle = 6;
int i = 0;
while(i < length && haystack[i] != needle)
i++;
if(haystack[i] != needle)
printf("needle not found!\n");
else
printf("found needle (%i) at position (%i)\n", needle, i);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment