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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!