Skip to content

Instantly share code, notes, and snippets.

@giljr
Created November 29, 2021 21:19
Show Gist options
  • Save giljr/a0dc608ee8138905111b389efdd229ad to your computer and use it in GitHub Desktop.
Save giljr/a0dc608ee8138905111b389efdd229ad to your computer and use it in GitHub Desktop.
Linear Search
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int SequentialSearch(int vec[], int sought);
#define VECTORSIZE 10
int main()
{
int vec[VECTORSIZE] = { 0 };
int sought, found, i;
srand(time(NULL));
// Entering data
for (int i = 0; i < VECTORSIZE; i++)
vec[i] = rand() % 1000;
printf("Sequential Search Algorithm\n");
printf("Vector Generation:\n");
for (int i = 0; i < VECTORSIZE; i++)
printf("%d\t", vec[i]);
printf("\nSelect a value to search: ");
scanf_s("%d", &sought);
found = SequentialSearch(vec, sought);
if (found == -1)
printf("\nValue not found. \n");
else
printf("Value found in the position %d. \n", found);
system("pause");
return 0;
}
int SequentialSearch(int vec[], int sought)
{
int found, i;
found = 0;
i = 0;
while ((i <= VECTORSIZE) && (found == 0))
{
if (vec[i] == sought)
found = 1;
else
i++;
}
if (found == 0)
return -1;
else
return i + 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment