Mojo Sorting & Searching
Putting values in order and finding things in them are two jobs you’ll do in almost every program. Mojo has a built-in sort() function that sorts a list in place, and it accepts your own compare function when the normal order isn’t what you want. For searching, you’ve got in, try_index(), plain loops, and a fast binary search for data that’s already sorted. If you’re coming from Python, the biggest change is that there’s no sorted() and no .sort() method: it’s sort(my_list).
Sorting a list
Section titled “Sorting a list”sort() is built in, so there’s nothing to import. It changes the list in place and returns nothing:
def main(): var nums: List[Int] = [42, 7, 19, 3, 25] sort(nums) print(nums)
var names: List[String] = ["Mia", "ada", "Bo", "cy"] sort(names) print(names)Output:
[3, 7, 19, 25, 42][Bo, Mia, ada, cy]Numbers go from smallest to largest. Strings are compared byte by byte, which puts uppercase letters before lowercase ones: "Bo" and "Mia" come before "ada". Python does exactly the same. A bit further down you’ll see how to sort without caring about case.
Because sort() changes the list, the original order is gone afterwards. If you need to keep it, sort a copy:
def main(): var arrivals: List[String] = ["Cy", "Ada", "Bo"] var alphabetical = arrivals.copy() sort(alphabetical) print("arrived:", arrivals) print("sorted: ", alphabetical)Output:
arrived: [Cy, Ada, Bo]sorted: [Ada, Bo, Cy]Sorting part of a list, or an array
Section titled “Sorting part of a list, or an array”sort() actually takes a Span, a view into the data. A List or an Array turns into one automatically, and so does a slice. That means you can sort just part of a list:
def main(): var queue: List[Int] = [9, 8, 7, 6, 5, 4] sort(queue[1:4]) print(queue)
var dice = [6, 2, 5] sort(dice) print(dice)Output:
[9, 6, 7, 8, 5, 4][2, 5, 6]Only positions 1 to 3 were sorted; the rest stayed put. Mojo Span explains views in detail.
Sorting in your own order
Section titled “Sorting in your own order”To sort in a different order, give sort() a compare function as a second argument. It gets two values, a and b, and returns True if a should come before b:
def biggest_first(a: Int, b: Int) -> Bool: return a > b
def main(): var scores: List[Int] = [70, 95, 82, 61] sort(scores, biggest_first) print(scores)Output:
[95, 82, 70, 61]biggest_first says “a goes first when it’s bigger”, so the list ends up from high to low.
For a short compare function, a lambda saves you from naming it:
def main(): var words: List[String] = ["kiwi", "fig", "banana", "apple"] sort(words, lambda (a: String, b: String) -> Bool: a.byte_length() < b.byte_length()) print(words)
var names: List[String] = ["Mia", "ada", "Bo", "cy"] sort(names, lambda (a: String, b: String) -> Bool: a.lower() < b.lower()) print(names)Output:
[fig, kiwi, apple, banana][ada, Bo, cy, Mia]The first sort is by length. The second compares lowercase versions of the names, so case no longer matters, but the names themselves keep their original spelling. This is how you do what Python’s key=str.lower does.
Sorting records
Section titled “Sorting records”A list of tuples sorts field by field by default: first by the first value, and only when those are equal, by the second. A compare function lets you sort by any field you like:
def main(): var people: List[Tuple[String, Int]] = [("Cy", 30), ("Ada", 41), ("Bo", 25)]
sort(people) print(people)
sort(people, lambda (a: Tuple[String, Int], b: Tuple[String, Int]) -> Bool: a[1] < b[1]) print(people)Output:
[(Ada, 41), (Bo, 25), (Cy, 30)][(Bo, 25), (Cy, 30), (Ada, 41)]The first sort orders by name, because the name is the first field. The second compares a[1] and b[1], the ages.
Keeping equal items in order: stable sorts
Section titled “Keeping equal items in order: stable sorts”When two items compare as equal, the default sort() may put them in either order. Often you don’t care. Sometimes you do: if a list is already sorted by name and you sort it by age, you might want people of the same age to stay in name order. That’s called a stable sort, and you ask for it with sort[stable=True]:
def main(): var people: List[Tuple[String, Int]] = [("Ada", 25), ("Bo", 30), ("Cy", 25), ("Di", 30)] sort[stable=True](people, lambda (a: Tuple[String, Int], b: Tuple[String, Int]) -> Bool: a[1] < b[1]) print(people)Output:
[(Ada, 25), (Cy, 25), (Bo, 30), (Di, 30)]Within each age, the names are still in their old order (Ada before Cy, Bo before Di). Python’s sort is always stable; in Mojo you choose, and the default is not stable. The [stable=True] part is a compile-time parameter, which you’ll learn about in Mojo Parameters.
Searching a list
Section titled “Searching a list”You’ve met the simple searches in Mojo Lists. Here they are together:
def main(): var langs: List[String] = ["mojo", "rust", "zig", "rust"] print("zig" in langs) print(langs.count("rust")) print(langs.try_index("rust")) print(langs.try_index("go"))Output:
True21Nonein answers yes or no. count tells you how many matches there are. try_index gives the position of the first match as an Optional[Int], or None when there isn’t one (Mojo Optional covers how to use it).
When you’re looking for something that matches a condition, not one exact value, write a loop:
def main(): var temps: List[Int] = [12, 19, 7, 23, 15]
var hottest = temps[0] for t in temps: if t > hottest: hottest = t print("hottest:", hottest)
for i, t in enumerate(temps): if t > 20: print("first day above 20:", i) breakOutput:
hottest: 23first day above 20: 3Mojo’s max() and min() work on separate values like max(3, 7), but not on a whole list, so finding the largest item is a short loop.
Binary search on sorted data
Section titled “Binary search on sorted data”in and try_index look at items one by one. That’s fine for small lists. For a big list that’s already sorted, binary search is much faster: it looks at the middle, throws away the half that can’t contain the value, and repeats. Spans have it built in as binary_search_by():
def main(): var ids: List[Int] = [3, 8, 15, 23, 42, 57, 91] var target = 42 var pos = Span(ids).binary_search_by(lambda (x: Int) {imm target} -> Int: x - target) print(pos)
target = 50 pos = Span(ids).binary_search_by(lambda (x: Int) {imm target} -> Int: x - target) print(pos)Output:
4NoneHere’s what’s going on:
Span(ids)makes a view of the list, becausebinary_search_byis aSpanmethod.- The lambda tells the search where it stands. It must return a negative number if
xis smaller than what you want, zero for a match, and a positive number ifxis bigger.x - targetdoes exactly that for numbers. {imm target}is a capture list: it lets the lambda readtargetfrommain. Capture lists are explained in the Mojo manual’s page on closures.- The result is an
Optional[Int]: the position, orNone.
Coming from Python?
Section titled “Coming from Python?”| Python | Mojo | |
|---|---|---|
| Sort in place | xs.sort() |
sort(xs) |
| Sorted copy | sorted(xs) |
var ys = xs.copy(), then sort(ys) |
| Reverse order | xs.sort(reverse=True) |
sort(xs, lambda (a: Int, b: Int) -> Bool: a > b) |
| Sort by a key | key=len |
A compare function: a.byte_length() < b.byte_length() |
| Stable? | Always | Only with sort[stable=True] |
| Largest item | max(xs) |
A short loop |
| Binary search | bisect module |
Span(xs).binary_search_by(...) |
Practice
Section titled “Practice”1. Top three
Section titled “1. Top three”Sort the scores [55, 91, 78, 99, 64, 85] from highest to lowest, then print the top three.
Hint: sort with a compare function that returns a > b, then slice [0:3].
Show solution
def main(): var scores: List[Int] = [55, 91, 78, 99, 64, 85] sort(scores, lambda (a: Int, b: Int) -> Bool: a > b) print("top three:", scores[0:3])Output:
top three: [99, 91, 85]After sorting from high to low, the first three items are the three best scores. The slice is a view, so nothing extra is copied.
2. By length, then alphabetically
Section titled “2. By length, then alphabetically”Sort ["pear", "fig", "apple", "kiwi", "date"] by length. When two words have the same length, put them in alphabetical order. The result should be [fig, date, kiwi, pear, apple].
Hint: in the compare function, if the lengths differ, compare lengths. Otherwise, compare the words.
Show solution
def shorter_first(a: String, b: String) -> Bool: if a.byte_length() != b.byte_length(): return a.byte_length() < b.byte_length() return a < b
def main(): var fruits: List[String] = ["pear", "fig", "apple", "kiwi", "date"] sort(fruits, shorter_first) print(fruits)Output:
[fig, date, kiwi, pear, apple]The second comparison only matters for words of the same length, so the three four-letter words end up in alphabetical order.
3. Fix the program
Section titled “3. Fix the program”This program should print the names in order and keep the original list too. It doesn’t compile. Fix it.
def main(): var names: List[String] = ["Cy", "Ada", "Bo"] var ordered = sorted(names) print(names, ordered)Hint: Mojo has no sorted(). Copy the list, then sort the copy.
Show solution
def main(): var names: List[String] = ["Cy", "Ada", "Bo"] var ordered = names.copy() sort(ordered) print(names, ordered)Output:
[Cy, Ada, Bo] [Ada, Bo, Cy]sort() changes the list you give it, so sorting a copy keeps the original order in names.
sort(xs)sorts a list, an array or a slice in place. There’s no.sort()method and nosorted().- Strings sort byte by byte, so uppercase comes before lowercase.
- Pass a compare function for your own order: it returns
Truewhenamust come strictly beforeb. - Tuples sort field by field. Use a compare function to sort by another field.
sort[stable=True]keeps equal items in their original order. The default sort isn’t stable.- Search with
in,count,try_indexor a loop. For big sorted data, useSpan(xs).binary_search_by(...).
Next up: strings in depth, splitting, joining, searching and slicing text, and what a “character” really is.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- sort API docs: both forms of
sort(), with and without a compare function. - Span API docs:
binary_search_by()and the otherSpanmethods. - Mojo manual: Lambda expressions: writing short functions inline, like the compare functions on this page.
- Mojo manual: Closures: capture lists such as
{imm target}.