Ternary Search in C++ Last Updated : 08 Jul, 2024 Summarize Comments Improve Suggest changes Share Like Article Like Report Ternary search is an efficient search algorithm used to find an element in a sorted array. It is a more efficient version of the binary search. In this article, we will learn how to implement the ternary search in C++.How Ternary Search Works?Ternary search divides the array (or search space) into three parts by calculating two midpoints, then it compares the target value with the elements at these midpoints to determine which segment to search next. This process continues recursively until the target element is found or the search space is empty.Algorithm for Ternary Search in C++Start by initializing two pointers, left and right, which initially point to the first and last elements of the array, respectively.Divide the current search space into three parts by calculating two midpoints, mid1 and mid2:mid1 is calculated as left + (right - left) / 3mid2 is calculated as right - (right - left) / 3This division effectively splits the array into [left, mid1], (mid1, mid2), and [mid2, right] segments.Check if the target value equals the elements at mid1 or mid2. If found, return the index of the target element.If the target is less than the element at mid1, update the right pointer to mid1 - 1 to search in the [left, mid1-1] segment.If the target is greater than the element at mid2, update the left pointer to mid2 + 1 to search in the [mid2+1, right] segment.If the target is between the elements at mid1 and mid2, update the left pointer to mid1 + 1 and the right pointer to mid2 - 1 to search in the (mid1+1, mid2-1) segment.Repeat the process with the updated search space until the target is found or the search space is exhausted.If the target is not found after exhausting the search space, return a value indicating that the target is not present in the array.C++ Program to Implement Ternary Search C++ #include <iostream> using namespace std; int ternarySearch(int arr[], int l, int r, int key) { while (r >= l) { int mid1 = l + (r - l) / 3; int mid2 = r - (r - l) / 3; // Check if the key is present at mid1 if (arr[mid1] == key) { return mid1; } // Check if the key is present at mid2 if (arr[mid2] == key) { return mid2; } // Determine which segment to search next if (key < arr[mid1]) { r = mid1 - 1; } else if (key > arr[mid2]) { l = mid2 + 1; } else { l = mid1 + 1; r = mid2 - 1; } } // If the element is not found return -1; } int main() { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int n = sizeof(arr) / sizeof(arr[0]); int key = 5; int index = ternarySearch(arr, 0, n - 1, key); if (index != -1) { cout << "Element found at index " << index << endl; } else { cout << "Element not found in the array" << endl; } return 0; } OutputElement found at index 4 Time ComplexityBest, Average, and Worst Case:Best Case: O(1), if the target element is found at one of the division points.Average and Worst Case: O(log3n), as each step reduces the array size to about one-third, so it takes about O(log3n)steps to narrow down to the target element.Space ComplexityIterative Version: O(1)Recursive Version: O(log3n)Ternary Search vs. Binary Search in C++Ternary search and binary search are both divide-and-conquer algorithms used to find elements in a sorted array. Binary search splits the search space in half, checking the middle element, and then discarding the half where the target cannot be. Ternary search, on the other hand, splits the array into three parts by checking two midpoints. While ternary search reduces the search space more aggressively, it involves more comparisons and computational overhead per iteration. As a result, binary search often performs better in practice due to its lower constant factors, despite having a similar logarithmic time complexity. Comment More infoAdvertise with us M mguru4c05q Follow Improve Article Tags : C++ CPP-DSA Practice Tags : CPP Similar Reads C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to 5 min read Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co 11 min read Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance 10 min read Object Oriented Programming in C++ Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th 5 min read Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact 12 min read Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and 9 min read 30 OOPs Interview Questions and Answers [2025 Updated] Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is 15 min read 3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power 13 min read Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca 7 min read CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi 6 min read Like