Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Informix Database Administrators Survival Guide

Authors: Joe Lumbley

1st Edition

0131243144, 978-0131243149

More Books

Students also viewed these Databases questions