Skip to content

Commit b42fd5a

Browse files
authored
Add Insertion Sort in Fortran (#5244)
1 parent 439ed23 commit b42fd5a

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
program insertionsort
2+
implicit none
3+
character(len=256) input1
4+
character(len=256) output
5+
character(len=10) :: integer_number
6+
integer, allocatable :: numbers(:)
7+
integer :: i
8+
9+
if(command_argument_count() /= 1) call usage()
10+
call get_command_argument(1, input1)
11+
if(input1 == "") call usage()
12+
call convert_to_array(input1, numbers)
13+
14+
if(size(numbers) == 1) call usage()
15+
16+
call insertion_sort(numbers)
17+
18+
output = ""
19+
do i = 1, size(numbers)
20+
write(integer_number, '(I0)') numbers(i)
21+
if(len_trim(output) == 0) then
22+
output = trim(integer_number)
23+
else
24+
output = trim(output) // ", " // trim(integer_number)
25+
end if
26+
end do
27+
print '(A)', trim(output)
28+
29+
30+
contains
31+
subroutine usage()
32+
write(*,'(a)') 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'
33+
stop
34+
end subroutine usage
35+
36+
subroutine convert_to_array(input1, numbers)
37+
implicit none
38+
character(len=*), intent(in) :: input1
39+
integer, allocatable, intent(out) :: numbers(:)
40+
integer :: i, length, pos, io_status
41+
42+
length = 1
43+
do i = 1, len_trim(input1)
44+
if (input1(i:i) == ',') length = length + 1
45+
end do
46+
47+
allocate(numbers(length))
48+
49+
pos = 1
50+
do i = 1, length
51+
read(input1(pos:), *, iostat=io_status) numbers(i)
52+
if (io_status /= 0) call usage()
53+
pos = index(input1(pos:), ',') + pos
54+
end do
55+
end subroutine convert_to_array
56+
57+
subroutine insertion_sort(numbers)
58+
implicit none
59+
integer, intent(inout) :: numbers(:)
60+
integer :: i, j, temp
61+
62+
do i = 2, size(numbers)
63+
temp = numbers(i)
64+
j = i - 1
65+
66+
do while (j >= 0 .and. numbers(j) > temp)
67+
numbers(j+1) = numbers(j)
68+
j = j - 1
69+
end do
70+
numbers(j+1) = temp
71+
end do
72+
73+
end subroutine insertion_sort
74+
end program insertionsort

0 commit comments

Comments
 (0)