Question
HI i need help my code is malfunctioning at the same exact point the point here is cout < < Enter the array elements :
HI i need help my code is malfunctioning at the same exact point the point here is cout << "Enter the array elements : "; int a[n]; for (int i = 0; i < n; i++) { cin >> a[i]; } the full code is
using namespace std; #include
// recursive function tertiary search int tertiary_search(int ar[], int l, int r, int k) { if (l <= r) { // Find the mid1 and mid2 int mid1 = l + (r - l) / 3; int mid2 = r - (r - l) / 3; // Check if k is present at mid1 or mid2 if (ar[mid1] == k) { return mid1; } if (ar[mid2] == k) { return mid2; } if (k < ar[mid1]) { // The k lies in between l and mid1 return tertiary_search(ar, l, mid1 - 1, k); } else if (k > ar[mid2]) { // The k lies in between mid2 and r return tertiary_search(ar, mid2 + 1, r, k); } else { // The k lies in between mid1 and mid2 return tertiary_search(ar, mid1 + 1, mid2 - 1, k); } } // value not found return -1; } int main() { cout << "Enter the number of elements : "; int n; cin >> n;
// make sure the array you enter should be sorted since binary and tertiary search work on sorted array cout << "Enter the array elements : "; int a[n]; for (int i = 0; i < n; i++) { cin >> a[i]; }
cout << "Enter the value to search : "; int k; cin >> k; int ans = tertiary_search(a, 0, n - 1, k); if (ans == -1) { cout << k << " not found " << endl; } else { cout << k << " found at index : " << ans << endl; } return 0; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started