Anonymous user
Sorting algorithms/Bubble sort: Difference between revisions
Added GDScript implementation.
imported>Avethenoul m (Fixed a small indexing error in Befunge example) |
imported>LongPtrCall (Added GDScript implementation.) |
||
Line 3,918:
(1 2 3)
</syntaxhighlight>
=={{header|GDScript}}==
Here is an implementation of Bubble Sort algorithm in GDScript for array of primitive types:
<syntaxhighlight lang="gdscript">
extends Node2D
func BubbleSort(_array : Array) -> void:
for i in range(_array.size() - 1):
var swapped : bool = false
for j in range(_array.size() - i - 1):
if _array[j] > _array[j + 1]:
var tmp = _array[j]
_array[j] = _array[j + 1]
_array[j + 1] = tmp
swapped = true
if not swapped:
break
return
func _ready() -> void:
var array : Array = range(-10, 10)
array.shuffle()
print("Initial array:")
print(array)
BubbleSort(array)
print("Sorted array:")
print(array)
return
</syntaxhighlight>
Possible output:
{{out}}
<pre>
Initial array:
[-7, -6, 2, -8, 4, -1, -3, -5, 5, -10, -4, 7, 3, 8, 0, -9, 6, 9, -2, 1]
Sorted array:
[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</pre>
If you need to sort objects, this can be done in way like this:
<syntaxhighlight lang="gdscript">
class Comparable:
var Value
func _init(_val):
self.Value = _val
func compare(_other : Comparable) -> int:
# Here is the simple implementation of compare
# for primitive type wrapper.
return self.Value - _other.Value
func BubbleSortObjects(_array : Array) -> void:
for i in range(_array.size() - 1):
var swapped : bool = false
for j in range(_array.size() - i - 1):
if _array[j].compare(_array[j + 1]) > 0:
var tmp = _array[j]
_array[j] = _array[j + 1]
_array[j + 1] = tmp
swapped = true
if not swapped:
break
return
</syntaxhighlight>
This approach is slow though. To sort array of primitive types use Array.sort() method instead.
To sort array of objects you can use Array.sort_custom(func : Callable) method.
=={{header|Go}}==
|