-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask2.cpp
More file actions
98 lines (95 loc) · 2.46 KB
/
task2.cpp
File metadata and controls
98 lines (95 loc) · 2.46 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
//Task 2
#include <bits/stdc++.h>
using namespace std;
//Sequential search
int sequential_search(const vector<int>& arr, int target)
{
for (int i = 0; i < arr.size(); i++)
if (arr[i] == target){return i;}
return -1;
}
//Recursive Sequential search
int recursive_sequential_search(const vector<int>& arr, int target, int index = 0)
{
if (index == arr.size())
return -1;
if (arr[index] == target)
return index;
return recursive_sequential_search(arr,target,index+1);
}
//Binary_Search
int binary_search(const vector<int>& arr, int target)
{
int low = 0;
int high = arr.size()-1;
while (low <= high)
{
int mid = (low + high)/2;
if (arr[mid] == target)
return mid;
else if (arr[mid] < target)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
//Recursive Binary Search
int recursive_binary_search(const vector<int>& arr, int target,int low,int high)
{
if (low > high)
return -1;
int mid = (low + high)/2;
if (arr[mid] == target)
return mid;
if (arr[mid] < target)
return recursive_binary_search(arr,target,mid+1,high);
return recursive_binary_search(arr,target,low,mid-1);
}
int main()
{
cout<<"Enter number of elements in array(Array size must be positive): ";
int n ;
cin >> n;
cout<<"Enter elements: (Elements must be positive)";
vector<int> num ;
for (int i = 0; i < n; i++)
{
int value;
cin >> value;
num.push_back(value);
}
cout<<"Enter target: ";
int target;
cin>>target;
cout << "\nChoose searching method:\n";
cout << "1 - Sequential Search\n";
cout << "2 - Recursive Sequential Search\n";
cout << "3 - Binary Search\n";
cout << "4 - Recursive Binary Search\n";
cout << "Enter your choice: ";
int choice ;
cin>>choice;
int result =-1;
switch (choice) {
case 1:
result = sequential_search(num, target);
break;
case 2:
result = recursive_sequential_search(num, target);
break;
case 3:
result = binary_search(num, target);
break;
case 4:
result = recursive_binary_search(num, target, 0, num.size() - 1);
break;
default:
throw invalid_argument("Invalid search method choice.");
}
if (result >= 0)
cout << "Target found at index " << result << endl;
else
cout << "Target not found" << endl;
return 0;
}