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
#include <stdio.h>

int ternarySearch(int l, int r, int key, const int arr[], int n) {
    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
}

int main(void) {
    int arr[] = {1, 2, 8, 14, 15, 64, 78, 89, 99, 100, 110, 123};
    int n = sizeof(arr) / sizeof(arr[0]);

    int tosearch = 89;

    int index = ternarySearch(0, n - 1, tosearch, arr, n);

    if (index != -1)
        printf("Element found at index: %d\n", index);
    else
        printf("Element not found.\n");

    return 0;
}



/*
run:

Element found at index: 7

*/

 



answered Jan 11 by avibootz
edited Jan 12 by avibootz

Related questions

...