1. One third
Split the active range into thirds.
const third = Math.floor((right - left) / 3)Typorithm · medium
Step 1 of 8 · intro card
Search Algorithms
Ternary Search splits a sorted range into three parts using two probe indexes.
Ternary Search is a sorted-array search pattern.
It checks two middle points instead of one.
Those two checks decide whether to keep the left third, middle third, or right third.
It is logarithmic, but Binary Search is usually simpler and uses fewer comparisons.
Requires sorted input.
Compute mid1 and mid2.
Check both split points.
Discard one or two thirds.
Usually not better than Binary Search for arrays.
function ternarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const third = Math.floor((right - left) / 3);
const mid1 = left + third;
const mid2 = right - third;
if (arr[mid1] === target) return mid1;
if (arr[mid2] === target) return mid2;
if (target < arr[mid1]) right = mid1 - 1;
else if (target > arr[mid2]) left = mid2 + 1;
else {
left = mid1 + 1;
right = mid2 - 1;
}
}
return -1;
}Connect each part of the code to the concept before you type.
Split the active range into thirds.
const third = Math.floor((right - left) / 3)mid1 marks the end of the left third.
const mid1 = left + thirdmid2 marks the start of the right third.
const mid2 = right - thirdReturn if the target is at the first split point.
if (arr[mid1] === target) return mid1If target is below mid1, keep only the left third.
if (target < arr[mid1]) right = mid1 - 1If target is above mid2, keep only the right third.
else if (target > arr[mid2]) left = mid2 + 1Otherwise keep the middle third between mid1 and mid2.
left = mid1 + 1Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputArray [1,3,5,7,9,11,13,15] · target 9
Follow temporary values, local state and supporting structures at this step.
Local state · indices and saved values
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state