Sorting algorithms/Gnome sort: Difference between revisions
Content added Content deleted
Line 630: | Line 630: | ||
<lang Eiffel> |
<lang Eiffel> |
||
class |
class |
||
GNOME_SORT |
GNOME_SORT [G -> COMPARABLE] |
||
feature |
feature |
||
⚫ | |||
sort (ar: ARRAY [G]): ARRAY [G] |
|||
-- sort array ar with gnome sort |
|||
require |
|||
array_not_void: ar/= VOID |
array_not_void: ar /= VOID |
||
local |
|||
i,j |
i, j: INTEGER |
||
⚫ | |||
ith: G |
|||
⚫ | |||
⚫ | |||
create Result.make_empty |
|||
⚫ | |||
⚫ | |||
⚫ | |||
from |
|||
⚫ | |||
⚫ | |||
j := 3 |
|||
until |
|||
i > Result.count |
|||
loop |
|||
if Result [i - 1] <= Result [i] then |
|||
i := j |
|||
j := j + 1 |
|||
else |
|||
ith := Result [i - 1] |
|||
i:= |
Result [i - 1] := Result [i] |
||
Result [i] := ith |
|||
i := i - 1 |
|||
if i = 1 then |
|||
⚫ | |||
j := j + 1 |
|||
⚫ | |||
end |
end |
||
end |
end |
||
⚫ | |||
⚫ | |||
ensure |
ensure |
||
same_length: ar.count = Result.count |
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 |
|||
⚫ | |||
⚫ | |||
Result := TRUE |
|||
from |
|||
i := ar.lower |
|||
⚫ | |||
i = ar.upper |
|||
⚫ | |||
if ar [i] > ar [i + 1] then |
|||
RESULT := FALSE |
|||
⚫ | |||
i := i + 1 |
|||
end |
|||
end |
|||
end |
end |
||
</lang> |
</lang> |
||
Test: |
Test: |
||
Line 673: | Line 700: | ||
class |
class |
||
APPLICATION |
APPLICATION |
||
inherit |
|||
ARGUMENTS |
|||
create |
create |
||
make |
|||
feature |
feature |
||
make |
|||
⚫ | |||
do |
|||
test:= <<7, 99, -7, 1, 0, 25, -10>> |
test := <<7, 99, -7, 1, 0, 25, -10>> |
||
⚫ | |||
io.put_string ("unsorted:%N") |
|||
⚫ | |||
across |
|||
⚫ | |||
test as ar |
|||
⚫ | |||
loop |
|||
⚫ | |||
end |
|||
io.new_line |
|||
io.put_string ("sorted:%N") |
|||
⚫ | |||
⚫ | |||
across |
|||
test as ar |
|||
loop |
|||
io.put_string (ar.item.out + "%T") |
|||
end |
|||
end |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
end |
end |
||
</lang> |
</lang> |
||
OUTPUT: |
OUTPUT: |
||
<pre> |
<pre> |
||
Unsorted: |
Unsorted: |
||
7 99 -7 1 0 25 -10 |
|||
Sorted: |
|||
-7 -10 0 1 7 25 99 |
|||
</pre> |
</pre> |
||