0% found this document useful (0 votes)
59 views

Linear and Binary Search

Uploaded by

techyvlogs81
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views

Linear and Binary Search

Uploaded by

techyvlogs81
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

/*Linear Search and Binary Search*/

#include<stdio.h>
void linearSearch(int arr[10], int n, int key){
int flag=0, i;
for(i=0; i<n; i++){
if(key == arr[i]){
flag=1;
break;
}
}
if(flag==1){
printf("Element found at location %d\n", i);
}
else{
printf("Element not found.");
}
}

void binarySearch(int arr[10], int n, int key) {


int low = 0, high = n - 1, mid;
int flag = 0, foundIndex = -1;

while (low <= high) {


mid = (low + high) / 2;
if (arr[mid] == key) {
flag = 1;
foundIndex = mid;
break;
} else if (key > arr[mid]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
if (flag == 1) {
printf("Element found at location: %d\n", foundIndex);
} else {
printf("Element not found.\n");
}
}
void main(){
int arr[10], i, n, a, key;
printf("Enter limit: ");
scanf("%d", &n);
printf("Enter elements into array:\n");
for(i=0; i<n; i++){
scanf("%d", &arr[i]);
}
printf("Enter element to be searched: ");
scanf("%d", &key);
printf("Select 1 or 2:\n1.Linear Search\n2.Binary Search\n");
printf("Enter selection: ");
scanf("%d", &a);
switch(a)
{
case 1: linearSearch(arr, n, key);

case 2: binarySearch(arr, n, key);


}
}

OUTPUT

You might also like