Exercise2 Ds
Exercise2 Ds
Recursive:
Source Code:
#include <stdio.h>
int RecursiveLS(int arr[], int value, int index, int n)
{
int pos = 0;
if(index >= n)
{
return 0;
}
else if (arr[index] == value)
{
pos = index + 1;
return pos;
}
else
{
return RecursiveLS(arr, value, index+1, n);
}
return pos;
}
int main()
{
int n, value, pos, m = 0, arr[100];
printf("Enter the total elements in the array ");
scanf("%d", &n);
printf("Enter the array elements\n");
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
printf("Enter the element to search ");
scanf("%d", &value);
pos = RecursiveLS(arr, value, 0, n);
if (pos != 0)
{
printf("Element found at pos %d ", pos);
}
else
{
printf("Element not found");
}
return 0;
}
OUTPUT:
Source Code:
#include<stdio.h>
int main()
{
int array[100], search, c, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d integer(s)\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter a number to search\n");
scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search)
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);
return 0;
}
OUTPUT:
Source Code:
#include <stdio.h>
int bs(int arr[], int l, int h, int x) {
if (l <= h) { // Correct base case
int mid = l + (h - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return bs(arr, l, mid - 1, x);
return bs(arr, mid + 1, h, x);
}
return -1; // Element not found
}
int main(void) {
int arr[100], n, i, x;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter array elements (sorted): ");
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("Enter search element: ");
scanf("%d", &x);
int res = bs(arr, 0, n - 1, x);
if (res == -1)
printf("Element is not found\n");
else
printf("Element %d is found at %d index\n", x, res);
return 0;
}
OUTPUT :
Source Code:
#include<stdio.h>
int bs(int arr[],int l,int h,int x)
{
while(l<=h)
{
int mid=(h+l)/2;
if(arr[mid]==x)
return mid;
if(arr[mid]<x)
l=mid+1;
else
h=mid-1;
}
return -1;
}
int main(void)
{
int arr[100],n,i,x;
printf("enter no.of elements :");
scanf("%d",&n);
printf("enter array elements:");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
printf("enter search element :");
scanf("%d",&x);
int res=bs(arr,0,n-1,x);
if(res==-1)
printf("element is not found");
else
printf("element %d is found at %d index ",x,res);
return 0;
}
OUTPUT: