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 VB.NET

1 Answer

0 votes
Imports System
				
Module TernarySearchDemo

    Function TernarySearch(l As Integer, r As Integer, key As Integer, arr As Integer()) As Integer
        While l <= r
            Dim mid1 As Integer = l + (r - l) \ 3
            Dim mid2 As Integer = r - (r - l) \ 3

            If arr(mid1) = key Then
                Return mid1
            End If

            If arr(mid2) = key Then
                Return mid2
            End If

            If key < arr(mid1) Then
                r = mid1 - 1
            ElseIf key > arr(mid2) Then
                l = mid2 + 1
            Else
                l = mid1 + 1
                r = mid2 - 1
            End If
        End While

        Return -1 ' not found
    End Function

    Sub Main()
        Dim arr As Integer() = {1, 2, 8, 14, 15, 64, 78, 89, 99, 100, 110, 123}

        Dim toSearch As Integer = 89

        Dim index As Integer = TernarySearch(0, arr.Length - 1, toSearch, arr)

        If index <> -1 Then
            Console.WriteLine("Element found at index: " & index)
        Else
            Console.WriteLine("Element not found.")
        End If

        Console.ReadLine()
    End Sub

End Module


' run:
'
' Element found at index: 7
'

 



answered Jan 12 by avibootz

Related questions

...