Sorting algorithms/Gnome sort: Difference between revisions

Line 630:
 
<lang Eiffel>
 
class
GNOME_SORT [G -> COMPARABLE]
 
feature
 
sort(ar: ARRAY[INTEGER]): ARRAY[INTEGER]
-- sort array (ar: withARRAY gnome[G]): sortARRAY [G]
-- sort array ar with gnome sort
require
array_not_void: ar /= VOID
local
i, j, ith: INTEGER
do
from ith: G
do
i:= 2
create Result.make_empty
j:= 3
Result.deep_copy := (ar)
until
i>ar.countfrom
i := 2
loop
if ar[i-1]j <:= ar[i] then3
i:= juntil
j:=i j+1> Result.count
elseloop
ithif :=Result ar[i - 1] <= Result [i] then
ar[ i-1] := ar[i]j
ar[i] j := ithj + 1
i:= i-1else
if ith i:=1 thenResult [i - 1]
Result [i - 1] :=j Result [i]
jResult [i] := j+1ith
i := i - 1
if i = 1 then
j i := 3j
j := j + 1
end
end
end
end
Result := ar
ensure
same_length: ar.count = Result.count
Result_is_sorted: is_sorted (Result)
same_items: Result.same_items (ar)
end
 
feature {NONE}
 
is_sorted (ar: ARRAY [G]): BOOLEAN
--- Is 'ar' sorted in ascending order?
require
ar_not_empty: ar.is_empty = FALSE
local
test i: ARRAY[INTEGER]
do
Result := TRUE
from
i := ar.lower
until
i = ar.upper
loop
if ar [i] > ar [i + 1] then
RESULT := FALSE
end
i := i + 1
end
end
 
end
 
</lang>
Test:
Line 673 ⟶ 700:
class
APPLICATION
 
inherit
ARGUMENTS
 
create
make
 
feature
 
make
do
do
test := <<7, 99, -7, 1, 0, 25, -10>>
create gnome
io.put_string ("unsorted:%N")
test:= gnome.sort (test)
across
across test as ar loop io.put_string( ar.item.out + "%T") end
test as ar
end
loop
across test as ar loop io.put_string ( ar.item.out + "%T") end
end
io.new_line
io.put_string ("sorted:%N")
create gnome
test test:= gnome.sort (test)
across
test as ar
loop
io.put_string (ar.item.out + "%T")
end
end
 
sort(artest: ARRAY[INTEGER]): ARRAY[INTEGER]
 
gnome: GNOME_SORT [INTEGER]
 
test: ARRAY[INTEGER]
gnome: GNOME_SORT[INTEGER]
end
 
</lang>
OUTPUT:
<pre>
Unsorted: 1 27 32 99 1 -7 3 5
Sorted:7 99 -7 1 1 3 5 27 320 99 25 -10
Sorted:
-7 -10 0 1 7 25 99
</pre>
 
Anonymous user