Sorting algorithms/Counting sort: Difference between revisions

Content added Content deleted
(→‎{{header|jq}}: space requirement is O(length))
Line 441: Line 441:


<lang Eiffel>
<lang Eiffel>

class
class
COUNTING_SORT
COUNTING_SORT

feature
feature

sort(ar: ARRAY[INTEGER]; min, max: INTEGER): ARRAY[INTEGER]
sort (ar: ARRAY [INTEGER]; min, max: INTEGER): ARRAY [INTEGER]
local
-- Sorted Array in ascending order.
count: ARRAY[INTEGER]
require
i, j, z: INTEGER
ar_not_void: ar /= Void
do
lowest_index_zero: ar.lower = 0
create count.make_filled (0, 0, max-min)
from
local
count: ARRAY [INTEGER]
i:= 0
i, j, z: INTEGER
until
do
i= ar.count
create Result.make_empty
loop
Result.deep_copy (ar)
count[ar[i]-min]:= count[ar[i]-min]+1
create count.make_filled (0, 0, max - min)
i:= i+1
from
i := 0
until
i = Result.count
loop
count [Result [i] - min] := count [Result [i] - min] + 1
i := i + 1
end
z := 0
from
i := min
until
i > max
loop
from
j := 0
until
j = count [i - min]
loop
Result [z] := i
z := z + 1
j := j + 1
end
i := i + 1
end
ensure
Result_is_sorted: is_sorted (Result)
end
end

across count as c loop io.put_string (c.item.out + "%T") end
feature {NONE}
z:= 0

from i:= min
is_sorted (ar: ARRAY [INTEGER]): BOOLEAN
until i>max
--- Is 'ar' sorted in ascending order?
loop
require
from j:= 0
ar_not_empty: ar.is_empty = FALSE
until j= count[i-min]
local
i: INTEGER
do
Result := TRUE
from
i := ar.lower
until
i = ar.upper
loop
loop
ar[z]:=i
if ar [i] > ar [i + 1] then
z:= z+1
RESULT := FALSE
j:= j+1
end
i := i + 1
end
end
i:= i+1
end
end

Result:= ar
end
end
end

</lang>
</lang>
TEST:
TEST:
Line 480: Line 517:
class
class
APPLICATION
APPLICATION

inherit
ARGUMENTS
create
create
make
make

feature
feature

make
make
do
do
create test.make_filled(0,0,5)
create test.make_filled (0, 0, 5)
test[0]:=-7
test [0] := -7
test[1]:=4
test [1] := 4
test[2]:=2
test [2] := 2
test[3]:=6
test [3] := 6
test[4]:=1
test [4] := 1
test[5]:=3
test [5] := 3
across test as t loop io.put_string (t.item.out + "%T") end
io.put_string ("unsorted:%N")
across
create count
test:=count.sort (test, -7, 6)
test as t
loop
across test as ar loop io.put_string (ar.item.out+"%T") end
io.put_string (t.item.out + "%T")
end
end
io.new_line
io.put_string ("sorted:%N")
create count
test := count.sort (test, -7, 6)
across
test as ar
loop
io.put_string (ar.item.out + "%T")
end
end

count: COUNTING_SORT
count: COUNTING_SORT

test: ARRAY[INTEGER]
test: ARRAY [INTEGER]

end
end

</lang>
</lang>
{{out}}
{{out}}
Line 508: Line 561:
-7 1 2 3 4 6
-7 1 2 3 4 6
</pre>
</pre>

=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
{{works with|Fortran|95 and later}}