mirror of
https://github.com/TheAlgorithms/C
synced 2024-11-22 05:21:49 +03:00
Update linear_search.c
A shorter and simple understandable code...
This commit is contained in:
parent
e5dad3fa8d
commit
1c042cbca4
@ -1,36 +1,20 @@
|
|||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
|
||||||
|
|
||||||
int linearsearch(int *arr, int size, int val)
|
int search(int array[], int n, int x) {
|
||||||
{
|
|
||||||
int i;
|
// Going through array sequencially
|
||||||
for (i = 0; i < size; i++)
|
for (int i = 0; i < n; i++)
|
||||||
{
|
if (array[i] == x)
|
||||||
if (arr[i] == val)
|
return i;
|
||||||
return 1;
|
return -1;
|
||||||
}
|
|
||||||
return 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
int main()
|
int main() {
|
||||||
{
|
int array[] = {2, 4, 0, 1, 9};
|
||||||
int n, i, v;
|
int x = 1;
|
||||||
printf("Enter the size of the array:\n");
|
int n = sizeof(array) / sizeof(array[0]);
|
||||||
scanf("%d", &n); // Taking input for the size of Array
|
|
||||||
|
|
||||||
int *a = (int *)malloc(n * sizeof(int));
|
int result = search(array, n, x);
|
||||||
printf("Enter the contents for an array of size %d:\n", n);
|
|
||||||
for (i = 0; i < n; i++)
|
|
||||||
scanf("%d", &a[i]); // accepts the values of array elements until the
|
|
||||||
// loop terminates//
|
|
||||||
|
|
||||||
printf("Enter the value to be searched:\n");
|
(result == -1) ? printf("Element not found") : printf("Element found at index: %d", result);
|
||||||
scanf("%d", &v); // Taking input the value to be searched
|
|
||||||
if (linearsearch(a, n, v))
|
|
||||||
printf("Value %d is in the array.\n", v);
|
|
||||||
else
|
|
||||||
printf("Value %d is not in the array.\n", v);
|
|
||||||
|
|
||||||
free(a);
|
|
||||||
return 0;
|
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user