Skip to content

Commit 2c6036e

Browse files
committed
fix: make cycle sort work with duplicate elements
Some logic in cycle sort assumed a random permutation of elements.
1 parent 6519336 commit 2c6036e

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

levels/cycle_sort.gd

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,11 @@ func next(action):
5454
return emit_signal("mistake")
5555
_index += 1
5656
if _index == array.size:
57+
# Skip over duplicates to avoid infinite cycling
58+
while _smaller != _pointer and array.at(_pointer) == array.at(_smaller):
59+
_smaller += 1
5760
array.swap(_pointer, _smaller)
58-
while array.at(_pointer) == _pointer + 1:
61+
while array.is_in_place(_pointer):
5962
_pointer += 1
6063
if _pointer == array.size:
6164
return emit_signal("done")

models/array_model.gd

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,17 @@ func sort(i, j):
8787
_array = front + sorted + back
8888
emit_signal("sorted", i, j)
8989

90+
func is_in_place(i):
91+
"""Check if the element at index i is in its correct place."""
92+
var less = 0
93+
var equal = 0
94+
for element in _array:
95+
if element < _array[i]:
96+
less += 1
97+
elif element == _array[i]:
98+
equal += 1
99+
return less <= i and i < less + equal
100+
90101
func get_size():
91102
return _array.size()
92103

0 commit comments

Comments
 (0)