Skip to content

Commit e5e385d

Browse files
committed
feat: add comb sort
1 parent 907db7c commit e5e385d

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

levels/comb_sort.gd

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
class_name CombSort
2+
extends ComparisonSort
3+
4+
const NAME = "COMB SORT"
5+
const ABOUT = """
6+
Comb sort is a variant of bubble sort that operates on gapped arrays.
7+
"""
8+
const CONTROLS = """
9+
If the two highlighted elements are out of order, hit LEFT ARROW to swap
10+
them. Otherwise, hit RIGHT ARROW to continue.
11+
"""
12+
13+
const SHRINK_FACTOR = 1.3
14+
const ACTIONS = {
15+
"SWAP": "Left",
16+
"CONTINUE": "Right",
17+
}
18+
var _gap: int = array.size / SHRINK_FACTOR
19+
var _index = 0 # First of two elements being compared
20+
var _end = array.size # Beginning of sorted subarray
21+
var _swapped = false
22+
23+
func _init(array).(array):
24+
pass
25+
26+
func next(action):
27+
if array.at(_index) > array.at(_index + _gap):
28+
if action != null and action != ACTIONS.SWAP:
29+
return emit_signal("mistake")
30+
array.swap(_index, _index + _gap)
31+
_swapped = true
32+
elif action != null and action != ACTIONS.CONTINUE:
33+
return emit_signal("mistake")
34+
_index += 1
35+
if _index + _gap >= array.size:
36+
if not _swapped and _gap == 1:
37+
emit_signal("done")
38+
_gap /= SHRINK_FACTOR
39+
_gap = max(_gap, 1)
40+
_index = 0
41+
_swapped = false
42+
43+
func get_effect(i):
44+
if i == _index or i == _index + _gap:
45+
return EFFECTS.HIGHLIGHTED
46+
if i >= _end:
47+
return EFFECTS.DIMMED
48+
return EFFECTS.NONE

project.godot

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,11 @@ _global_script_classes=[ {
3939
"language": "GDScript",
4040
"path": "res://levels/cocktail_sort.gd"
4141
}, {
42+
"base": "ComparisonSort",
43+
"class": "CombSort",
44+
"language": "GDScript",
45+
"path": "res://levels/comb_sort.gd"
46+
}, {
4247
"base": "Node",
4348
"class": "ComparisonSort",
4449
"language": "GDScript",
@@ -81,6 +86,7 @@ _global_script_class_icons={
8186
"BogoSort": "",
8287
"BubbleSort": "",
8388
"CocktailSort": "",
89+
"CombSort": "",
8490
"ComparisonSort": "",
8591
"InsertionSort": "",
8692
"MergeSort": "",

scripts/levels.gd

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ const LEVELS = [
88
QuickSort,
99
CocktailSort,
1010
ShellSort,
11+
CombSort,
1112
]
1213
const MIN_WAIT = 1.0 / 32 # Should be greater than maximum frame time
1314
const MAX_WAIT = 4

0 commit comments

Comments
 (0)