Sort And Reverse
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 76 of 92.
sort() puts the elements of an array in ascending order. It changes the array itself:
var scores := [5, 1, 9, 3]
scores.sort()
print(scores)[1, 3, 5, 9]sort() returns nothing, so print(scores.sort()) is an error. Sort first, then print.
Strings are sorted alphabetically, and uppercase letters come before lowercase ones: ["bob", "Cleo", "ana"] becomes ["Cleo", "ana", "bob"].
reverse() flips the current order of the array, without sorting it. To sort in descending order, sort first and then reverse:
var hp := [7, 2, 9, 4]
hp.reverse()
print(hp)
hp.sort()
hp.reverse()
print(hp)[4, 9, 2, 7]
[9, 7, 4, 2]Assigning an array to another variable does not copy it: both variables then use the same array, and sorting one sorts the other. To keep the original order, sort a copy made with duplicate():
var original := [5, 3, 9]
var sorted_copy := original.duplicate()
sorted_copy.sort()
print(original, " ", sorted_copy)[5, 3, 9] [3, 5, 9]Challenge
EasyThe program reads a line of whole numbers separated by commas into numbers (already written). Print three lines:
Original:and the numbers in their original orderAscending:and the numbers sorted from smallest to largestDescending:and the numbers sorted from largest to smallest
For the input 5,3,9,1, the output is:
Original: [5, 3, 9, 1]
Ascending: [1, 3, 5, 9]
Descending: [9, 5, 3, 1]Try it yourself
extends Node
func _ready():
var parts := OS.read_string_from_stdin().split(",")
var numbers: Array[int] = []
for part in parts:
numbers.append(int(part))
# Write your code below
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators10Functions
Declare a FunctionArgumentsReturnReturn TypesRecap - Sigma FunctionRecap - Validation FunctionDefault Values5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary OperatorPractice on your own: Online GDScript compiler