Menu
CoddyTech

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 icon

Challenge

Easy

The program reads a line of whole numbers separated by commas into numbers (already written). Print three lines:

  1. Original: and the numbers in their original order
  2. Ascending: and the numbers sorted from smallest to largest
  3. Descending: 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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online GDScript compiler