🎓 A1Learner
🔍
0 of 52 lessons completed

Julia Sorting and Searching

Sorting puts the items of a collection in order. Searching finds where a value sits in a collection.

Sort words in order

Sorting text puts the words in alphabetical order. The result is a new array.

words = ["pear", "apple", "kiwi"]
println(sort(words))
println(words)

Sort descending and find a position

The rev=true setting reverses the order. findfirst reports the position of a value.

nums = [1, 3, 5]
println(sort(nums, rev=true))
println(findfirst(isequal(3), nums))

Find extremes and count matches

argmax and argmin give positions, not values. count tests each item with an anonymous function.

nums = [1, 9, 3, 5]
println(argmax(nums))
println(argmin(nums))
println(count(x -> x > 2, nums))

Example

scores = [72, 95, 60, 88]
println(sort(scores))
println(sort(scores, rev=true))
println(argmax(scores))
println(count(x -> x >= 80, scores))

Key points

  • sort: a function that returns the items of a collection in order.
  • Use sort with rev=true to sort from largest to smallest.
  • Use findfirst with isequal to get the position of a value.
  • Use argmax to get the position of the largest value.
  • Use argmin to get the position of the smallest value.
  • Use count with an anonymous function to count items that pass a test.

In this example, sort shows the scores from smallest to largest and then from largest to smallest. The argmax result 2 is the position of 95 in the original array. The count result shows that two scores are at least 80.

Note

sort returns a new array and leaves the original array unchanged.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

What does argmax([4, 9, 2]) return?