Skip to content

Commit 18239f8

Browse files
authored
Added Binary Search in Fortran (#5229)
1 parent ff0f6bb commit 18239f8

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
program binarysearch
2+
implicit none
3+
character(len=256) :: input1
4+
character(len=10) :: input2
5+
integer :: key, left, right, middle, io_status, i, length, pos
6+
integer, allocatable :: numbers(:)
7+
logical :: searched
8+
9+
if(command_argument_count() < 2) call usage()
10+
11+
call get_command_argument(1, input1)
12+
call get_command_argument(2,input2)
13+
14+
if(input1 == "") call usage()
15+
16+
call convert_to_array(input1, numbers)
17+
18+
read(input2, fmt=*, iostat=io_status) key
19+
20+
do i = 1, size(numbers) - 1
21+
if(numbers(i) > numbers(i+1)) then
22+
call usage()
23+
end if
24+
end do
25+
26+
left = 1
27+
right = size(numbers)
28+
searched = binary_search(numbers,key, left, right)
29+
if (searched) then
30+
print '(a)', 'true'
31+
else
32+
print '(a)', 'false'
33+
end if
34+
35+
contains
36+
subroutine usage()
37+
write(*,'(a)') "Usage: please provide a list of sorted integers (""1, 4, 5, 11, 12"") and the integer to find (""11"")"
38+
stop
39+
end subroutine usage
40+
41+
subroutine convert_to_array(input1, numbers)
42+
implicit none
43+
character(len=*), intent(in) :: input1
44+
integer, allocatable, intent(out) :: numbers(:)
45+
integer :: i, length, pos, io_status
46+
47+
length = 1
48+
do i = 1, len_trim(input1)
49+
if (input1(i:i) == ',') length = length + 1
50+
end do
51+
52+
allocate(numbers(length))
53+
54+
pos = 1
55+
do i = 1, length
56+
read(input1(pos:), *, iostat=io_status) numbers(i)
57+
pos = index(input1(pos:), ',') + pos
58+
end do
59+
end subroutine convert_to_array
60+
61+
function binary_search(numbers, key, left, right) result(answer)
62+
implicit none
63+
logical :: answer
64+
integer, intent(in) :: key
65+
integer, intent(in) :: numbers(:)
66+
integer :: left
67+
integer :: right
68+
integer :: middle
69+
answer = .false.
70+
do while (left <= right)
71+
middle = (left + right) / 2
72+
if(numbers(middle) == key) then
73+
answer = .true.
74+
return
75+
else if(numbers(middle) > key) then
76+
right = middle - 1
77+
else
78+
left = middle + 1
79+
end if
80+
end do
81+
end function binary_search
82+
end program binarysearch

0 commit comments

Comments
 (0)