Anonymous user
Sorting algorithms/Gnome sort: Difference between revisions
→{{header|Eiffel}}
Line 630:
<lang Eiffel>
class
GNOME_SORT [G -> COMPARABLE]
feature
sort(ar: ARRAY[INTEGER]): ARRAY[INTEGER]▼
-- sort array ar with gnome sort
array_not_void: ar /= VOID
i, j
do▼
i:= 2 ▼
create Result.make_empty
j:= 3▼
until▼
loop▼
Result [i - 1] :=
i := i - 1
if i = 1 then
j := j + 1
end▼
end
end
▲ end
▲ Result := ar
ensure
same_length: ar.count = Result.count
Result_is_sorted: is_sorted (Result)
feature {NONE}
is_sorted (ar: ARRAY [G]): BOOLEAN
--- Is 'ar' sorted in ascending order?
require
ar_not_empty: ar.is_empty = FALSE
local
Result := TRUE
from
i := ar.lower
▲ until
i = ar.upper
▲ loop
if ar [i] > ar [i + 1] then
RESULT := FALSE
i := i + 1
end
end
end
</lang>
Test:
Line 673 ⟶ 700:
class
APPLICATION
create
feature
▲ 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
end
io.new_line
io.put_string ("sorted:%N")
▲ create gnome
across
test as ar
loop
io.put_string (ar.item.out + "%T")
end
end
gnome: GNOME_SORT [INTEGER]▼
▲ test: ARRAY[INTEGER]
▲ gnome: GNOME_SORT[INTEGER]
end
</lang>
OUTPUT:
<pre>
Unsorted:
Sorted:
-7 -10 0 1 7 25 99
</pre>
|