binary_search_int_int64 Function

private pure function binary_search_int_int64(arr, val) result(pos)

Arguments

Type IntentOptional Attributes Name
integer(kind=int64), intent(in) :: arr(:)
integer(kind=int64), intent(in) :: val

Return Value integer(kind=int64)


Contents


Source Code

        pure function binary_search_int_int64(arr, val) result(pos)
            integer(int64), intent(in) :: arr(:)
            integer(int64), intent(in) :: val
            integer(int64) :: pos

            integer(int64) :: hi, lo

            lo = 1
            hi = size(arr)

            if(hi < lo) then
                pos = -lo
                return
            end if

            do while(hi /= lo)
                pos = int((hi + lo) / 2.0_dp, kind=int64)

                if(arr(pos) == val) then
                    exit
                else if(val > arr(pos)) then
                    lo = pos + 1
                else
                    hi = pos
                end if
            end do

            if(hi == lo) then
                if(arr(hi) == val) then
                    pos = hi
                else
                    pos = -1
                end if
            end if

        end function binary_search_int_int64