Skip to content

Commit 8712c98

Browse files
committed
feat: add odd-even sort
1 parent d1e83bb commit 8712c98

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

levels/odd_even_sort.gd

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
ODD-EVEN SORT
3+
4+
Odd-even sort is a variant of bubble sort that alternates on elements at
5+
odd and even indices.
6+
7+
If the two highlighted elements are out of order, hit LEFT ARROW to swap
8+
them. Otherwise, hit RIGHT ARROW to continue.
9+
"""
10+
11+
class_name OddEvenSort
12+
extends ComparisonSort
13+
14+
const ACTIONS = {
15+
"SWAP": "Left",
16+
"CONTINUE": "Right",
17+
}
18+
var _index = 1
19+
var _swapped = false
20+
21+
func _init(array).(array):
22+
pass
23+
24+
func next(action):
25+
if array.at(_index) > array.at(_index + 1):
26+
if action != null and action != ACTIONS.SWAP:
27+
return emit_signal("mistake")
28+
array.swap(_index, _index + 1)
29+
_swapped = true
30+
elif action != null and action != ACTIONS.CONTINUE:
31+
return emit_signal("mistake")
32+
_index += 2
33+
if _index + 1 >= array.size:
34+
if _index % 2 == 0 and not _swapped:
35+
emit_signal("done")
36+
_index = 1 if _index % 2 == 0 else 0
37+
_swapped = false
38+
39+
func get_effect(i):
40+
if i == _index or i == _index + 1:
41+
return EFFECTS.HIGHLIGHTED
42+
return EFFECTS.NONE

project.godot

+6
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,11 @@ _global_script_classes=[ {
6565
"path": "res://levels/merge_sort.gd"
6666
}, {
6767
"base": "ComparisonSort",
68+
"class": "OddEvenSort",
69+
"language": "GDScript",
70+
"path": "res://levels/odd_even_sort.gd"
71+
}, {
72+
"base": "ComparisonSort",
6873
"class": "QuickSort",
6974
"language": "GDScript",
7075
"path": "res://levels/quick_sort.gd"
@@ -91,6 +96,7 @@ _global_script_class_icons={
9196
"CycleSort": "",
9297
"InsertionSort": "",
9398
"MergeSort": "",
99+
"OddEvenSort": "",
94100
"QuickSort": "",
95101
"SelectionSort": "",
96102
"ShellSort": ""

scripts/levels.gd

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ const LEVELS = [
1010
ShellSort,
1111
CombSort,
1212
CycleSort,
13+
OddEvenSort,
1314
]
1415
const MIN_WAIT = 1.0 / 32 # Should be greater than maximum frame time
1516
const MAX_WAIT = 4

0 commit comments

Comments
 (0)