' Given a sorted array/vector/list of distinct integers and a target value K,
' return the index if the target is found.
' If not, return the index where it would be if inserted in order.
Imports System
Imports System.Collections.Generic
Class Program
' Function to find the index of k or the position where it should be inserted - Using Binary Search
Public Shared Function SearchInsertPositionOfK(ByVal list As List(Of Integer), ByVal k As Integer) As Integer
Dim left As Integer = 0, right As Integer = list.Count - 1
While left <= right
Dim mid As Integer = left + (right - left) / 2
If list(mid) = k Then
Return mid
ElseIf list(mid) > k Then
right = mid - 1
Else
left = mid + 1
End If
End While
Return left
End Function
Public Shared Sub Main()
Dim list1 As List(Of Integer) = New List(Of Integer) From {
1, 3, 5, 6, 7, 8
}
Dim k1 As Integer = 5
Console.WriteLine(SearchInsertPositionOfK(list1, k1))
Dim list2 As List(Of Integer) = New List(Of Integer) From {
1, 3, 5, 6, 7, 8
}
Dim k2 As Integer = 2
Console.WriteLine(SearchInsertPositionOfK(list2, k2))
Dim list3 As List(Of Integer) = New List(Of Integer) From {
1, 3, 5, 6, 7, 8
}
Dim k3 As Integer = 9
Console.WriteLine(SearchInsertPositionOfK(list3, k3))
End Sub
End Class
' run:
'
' 2
' 1
' 6
'