Typorithm · medium

Ternary Search

▷ Interactive algorithm labternary-searchsearchsorted-arraythree-way-splitlogarithmic-time
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Ternary Search

0%

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.

Preparing algorithm lab…
01

Requires sorted input.

02

Compute mid1 and mid2.

03

Check both split points.

04

Discard one or two thirds.

05

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;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. One third

Split the active range into thirds.

const third = Math.floor((right - left) / 3)

2. First middle

mid1 marks the end of the left third.

const mid1 = left + third

3. Second middle

mid2 marks the start of the right third.

const mid2 = right - third

4. Check mid1

Return if the target is at the first split point.

if (arr[mid1] === target) return mid1

5. Left third

If target is below mid1, keep only the left third.

if (target < arr[mid1]) right = mid1 - 1

6. Right third

If target is above mid2, keep only the right third.

else if (target > arr[mid2]) left = mid2 + 1

7. Middle third

Otherwise keep the middle third between mid1 and mid2.

left = mid1 + 1

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Ternary Search: Visual Walkthrough & Practice · Typorithm | ApplyDjinn