0% found this document useful (0 votes)
3 views3 pages

Array Size Target I I Size I Array I Target I

Notes

Uploaded by

amankumar225680
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)
3 views3 pages

Array Size Target I I Size I Array I Target I

Notes

Uploaded by

amankumar225680
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/ 3

LINEAR SEARCH

• #include<stdio.h>
• int linearSearch(int array[],int size,int target){
• for(int i=0;i<size;i++){
• if(array[i]==target){
• return i;
• }
• }return -1;
• }
• int main(){
• int size =10;
• int array[10];
• for(int i=0;i<size;i++){
• printf("Enter the element of array: ");
• scanf("%d",&array[i]);}
• int target;
• printf("enter the target element");
• scanf("%d",&target);
• int result = linearSearch(array,size,target);
• if(result!=-1){
• printf("Target element found at index %d\n",result);

}
• else{
• printf("Target is not found in array\n");
• }
• return 0;
}
BINARY SEARCH(ITERATIVE)
• #include<stdio.h>

• //binary search with iterative approach

• int binary_search(int arr[],int key,int low ,int high){

• while(low<=high){

• int mid = low + (high - low)/2;

• if(arr[mid]==key)

• return mid;

• if(arr[mid]<key)

• low = mid +1;

• else

• high = mid -1;

• }return -1;

• }

• int main(){

• int size =10;

• int array[10];

• for(int i=0;i<size;i++){

• printf("Enter the element of array: ");

• scanf("%d",&array[i]);

• }int target;

• printf("enter the target element: ");

• scanf("%d",&target);

• int result =binary_search(array, target,0,size);

• if(result==-1){

• printf("key is not present in arr");

• }

• else{

• printf("key is present at index %d\n",result);

• }

• return 0;

• }
BINARY SEARCH(RECURSIVE)
• #include<stdio.h>

• //binary search with recursive approach

• int binary_search(int arr[],int key,int low ,int high){

• if (high >=low){

• int mid = low + (high - low)/2;

• if(arr[mid]==key)

• return mid;

• if (arr[mid]>key)

• return binary_search(arr,key, low , mid-1);

• return binary_search(arr,key,mid+1,high);

• }return -1;

• }

• int main(){

• int size =10;

• int array[10];

• for(int i=0;i<size;i++){

• printf("Enter the element of array: ");

• scanf("%d",&array[i]);

• }

• int target;

• printf("enter the target element: ");

• scanf("%d",&target);


int result =binary_search(array, target,0,size);

• if(result==-1){

• printf("key is not present in arr");

• }

• else{

• printf("key is present at index %d\n",result);

• }

• return 0;

• }

You might also like