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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,914 questions

51,847 answers

573 users

How to implement ternary search to find a value in a sorted array with C#

1 Answer

0 votes
using System;

class TernarySearchDemo
{
    public static int TernarySearch(int l, int r, int key, int[] arr) {
        while (l <= r) {
            int mid1 = l + (r - l) / 3;
            int mid2 = r - (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
    }

    static void Main()
    {
        int[] arr = { 1, 2, 8, 14, 15, 64, 78, 89, 99, 100, 110, 123 };

        int toSearch = 89;

        int index = TernarySearch(0, arr.Length - 1, toSearch, arr);

        if (index != -1)
            Console.WriteLine("Element found at index: " + index);
        else
            Console.WriteLine("Element not found.");
    }
}


/*
run:

Element found at index: 7

*/

 



answered Jan 12 by avibootz

Related questions

...