Bubble sort in GDScript (Godot Engine 2.1)
I was needed to sort some game objects by position on the screen. There are a lot of sorting algorithms, and simplest one is the Bubble Sort algorithm. It works fine for me because I have the small count of objects to sort.
There is the code example in GDScript that sorts simple array of numbers:
There is the code example in GDScript that sorts simple array of numbers:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var notes = [7,2,5,1] | |
print("notes:", notes) | |
for i in range(notes.size()-1, -1, -1): | |
#print("i:", i) | |
for j in range(1,i+1,1): | |
#print("J:", j) | |
if notes[j-1] > notes[j]: | |
var temp = notes[j-1] | |
notes[j-1] = notes[j] | |
notes[j] = temp | |
print("sorted notes:", notes) | |
#output: | |
#notes:[7,2,5,1] | |
#soreted notes:[1,2,5,7] |
Nice effort, since I am new to this sort thing.
ReplyDelete