-
Notifications
You must be signed in to change notification settings - Fork 0
/
DS01_Search_In_Arrays.cpp
50 lines (45 loc) · 1.35 KB
/
DS01_Search_In_Arrays.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include<iostream>
using namespace std;
void PrintArray(int arr[],int size);
void LinearSearch(int arr[],int size,int Key){
for(int i=0;i<size;i++){
if(arr[i]==Key){
cout<<"BY Linear Search ::: KEY "<<Key<<" FOUND AT INDEX "<<i<<" IN THE ARRAY ";
PrintArray(arr,size);
return;
}
}
cout<<"BY Linear Search ::: KEY "<<Key<<" NOT FOUND IN THE ARRAY ";
PrintArray(arr,size);
}
void BinarySearch(int arr[],int size,int Key){
int start=0,end=size-1;
while(start<=end){
int mid=(start+end)/2;
if(arr[mid]==Key){
cout<<"BY Binary Search ::: KEY "<<Key<<" FOUND AT INDEX "<<mid<<" IN THE ARRAY ";
PrintArray(arr,size);
return;
}
if(arr[mid]>Key){ end=mid-1; }
else { start=mid+1; }
}
cout<<"BY Binary Search ::: KEY "<<Key<<" NOT FOUND IN THE ARRAY ";
PrintArray(arr,size);
}
void PrintArray(int arr[],int size){
cout<<"{ ";
for(int i=0;i<size;i++){
if(i==(size-1)){ cout<<arr[i]<<" }"<<endl; }
else { cout<<arr[i]<<", "; }
}
}
int main(){
int key;
int arr[7]={1,2,3,4,5,6,7};
cout<<"ENTER THE KEY YOU WANT TO SEARCH IN THE ARRAY ::: ";
cin>>key;
LinearSearch(arr,7,key);
BinarySearch(arr,7,key);
return 0;
}