Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,709 questions

55,473 answers

573 users

How to implement ternary search to find a value in a sorted list with TypeScript

1 Answer

0 votes
function ternarySearch(l: number, r: number, key: number, arr: number[]): number {
    while (l <= r) {
        const mid1 = l + Math.floor((r - l) / 3);
        const mid2 = r - Math.floor((r - l) / 3);

        if (arr[mid1] === key) return mid1;
        if (arr[mid2] === key) return mid2;

        if (key < arr[mid1]) {
            r = mid1 - 1;
        } else if (key > arr[mid2]) {
            l = mid2 + 1;
        } else {
            l = mid1 + 1;
            r = mid2 - 1;
        }
    }

    return -1; // not found
}

function main(): void {
    const arr: number[] = [1, 2, 8, 14, 15, 64, 78, 89, 99, 100, 110, 123];
    const toSearch = 89;

    const index = ternarySearch(0, arr.length - 1, toSearch, arr);

    if (index !== -1) {
        console.log(`Element found at index: ${index}`);
    } else {
        console.log("Element not found.");
    }
}

main();



/*
run:

"Element found at index: 7" 

*/

 



answered Jan 12 by avibootz

Related questions

...