LAB PROGRAM DSA .WEEK 1
LAB PROGRAM DSA .WEEK 1
int main() {
int arr[100], size, target, i, result=0;
// Input the size of the array
printf("Enter the size of the array: ");
scanf("%d", &size);
// Input the key to search
printf("Enter the target to search: ");
scanf("%d", &target);
// Input the elements of the array
printf("Enter the elements of the
array:\n");
for(i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
for(i = 0; i < size; i++){
if(arr[i] == target) {
result=1;
break;
}
}
if (result==1)
{
printf("Element found at index
%d\n", i);
}
else {
printf("Element not found in the
array\n");
}
return 0;
}
1(b). Linear Search with function:
int main() {
int arr[100], size, target, i, result;
return 0;
}
#include <stdio.h>
int main() {
int size, target;
// Ask user for the size of the array
printf("Enter the size of the array: ");
scanf("%d", &size);
return 0;
}
#include <stdio.h>
int main() {
int n, i, key, low, high, mid;
int arr[n];
printf("Enter %d elements in sorted order: \n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
low = 0;
high = n - 1;
if (arr[mid] == key) {
printf("Key found at index %d\n", mid);
return 0;
} else if (arr[mid] < key) {
low = mid + 1;
} else {
high = mid - 1;
}
}
#include <stdio.h>
if (arr[mid] == key) {
return mid;
} else if (arr[mid] < key) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
int main() {
int n, i, key;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements in sorted order: \n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
if (result != -1) {
printf("Key found at index %d\n", result);
} else {
printf("Key not found\n");
}
return 0;
}
2 ( c) Recursive Binary Search with function:
#include <stdio.h>
int main() {
int n, i, key;
// Call the recursive binary search function and store the result
int result = binarySearchRecursive(arr, 0, n - 1, key);
return 0;
}
if arr[mid] == key:
return mid # Return the index if the key is found
elif arr[mid] < key:
low = mid + 1 # Search the right half
else:
high = mid - 1 # Search the left half