57
11.c
Normal file
57
11.c
Normal file
@@ -0,0 +1,57 @@
|
||||
#include <stdio.h>
|
||||
|
||||
int linear(int target, int arr[], int n) {
|
||||
for (int i = 0; i < n; i++)
|
||||
if (arr[i] == target)
|
||||
return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
int binary(int target, int arr[], int b, int e) {
|
||||
if (b > e)
|
||||
return -1;
|
||||
|
||||
int m = b + (e - b) / 2;
|
||||
|
||||
if (arr[m] == target)
|
||||
return m;
|
||||
|
||||
if (arr[m] > target)
|
||||
return binary(target, arr, b, m - 1);
|
||||
else
|
||||
return binary(target, arr, m + 1, e);
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
int main() {
|
||||
int const SIZE = 5;
|
||||
int arr[5], target, index;
|
||||
printf("------\nLinear:\n------\n");
|
||||
printf("Enter %d integers for the array:\n", SIZE);
|
||||
for (int i = 0; i < SIZE; i++) {
|
||||
printf("Element %d: ", i);
|
||||
scanf("%d", arr + i);
|
||||
}
|
||||
printf("Enter element to find: ");
|
||||
scanf("%d", &target);
|
||||
index = linear(target, arr, SIZE);
|
||||
if (index == -1)
|
||||
printf("Element not found\n");
|
||||
else
|
||||
printf("Element %d found at index %d\n", target, index);
|
||||
|
||||
printf("------\nBinary:\n------\n");
|
||||
printf("Enter %d SORTED integers for the array:\n", SIZE);
|
||||
for (int i = 0; i < SIZE; i++) {
|
||||
printf("Element %d: ", i);
|
||||
scanf("%d", arr + i);
|
||||
}
|
||||
printf("Enter element to find: ");
|
||||
scanf("%d", &target);
|
||||
index = binary(target, arr, 0, SIZE - 1);
|
||||
if (index == -1)
|
||||
printf("Element not found\n");
|
||||
else
|
||||
printf("Element %d found at index %d\n", target, index);
|
||||
}
|
Reference in New Issue
Block a user