The QuickSelect Selection algorithm finds the kth smallest item in a collection. It it related to QuickSort.
Test cases in Scala
assert(quickSelect(List(1, 2, 3, 4, 5), 3) == Some(3)) assert(quickSelect(List(5, 4, 3, 2, 1), 3) == Some(3)) assert(quickSelect(List(5, 4, 3, 2, 1), 1) == Some(1)) assert(quickSelect(List.empty[Int], 1) == None) assert(quickSelect(List(1), 1) == Some(1)) assert(quickSelect(List(1), 2) == None)
Algorithm in Scala
16 lines of Scala (version 2.13), showing how concise Scala can be!
The implementation is similar in principle to QuickSort, however we get a simplification because we do not need to care about certain values once we know where our minimum/maximum are after partitioning.
In this algorithm, we pick a pivot (the most straightforward is the first element), and then partition the remaining list by elements lower and higher than the pivot. (this is © from www.scala-algorithms.com)
After partitioning by the pivot, if the number of elements we need is higher than the number provided in the smaller partition, then we immediately look at the higher partition, eliminating a large number of elements.
Scala concepts & Hints
The 'Option' type is used to describe a computation that either has a result or does not. In Scala, you can 'chain' Option processing, combine with lists and other data structures. For example, you can also turn a pattern-match into a function that return an Option, and vice-versa!
In Scala, the 'Ordering' type is a 'type class' that contains methods to determine an ordering of specific types.
Pattern matching in Scala lets you quickly identify what you are looking for in a data, and also extract it.
Stack safety is present where a function cannot crash due to overflowing the limit of number of recursive calls.
This function will work for n = 5, but will not work for n = 2000 (crash with java.lang.StackOverflowError) - however there is a way to fix it :-)
In Scala Algorithms, we try to write the algorithms in a stack-safe way, where possible, so that when you use the algorithms, they will not crash on large inputs. However, stack-safe implementations are often more complex, and in some cases, overly complex, for the task at hand.
In Scala, tail recursion enables you to rewrite a mutable structure such as a while-loop, into an immutable algorithm.
Type classes are one of Scala's most important super-powers: they enable you to add new behaviour to existing classes, without modifying those classes. In many languages, to add a behaviour to a class, you would typically extend it with an interface, and then implement methods against this interface.This, however, does not scale: especially when you have older libraries, you would be forced to make them depend on a new interface, and have to re-build everything.
Type classes are used heavily in Apple's SwiftUI as "extensions" to enable powerful abstraction capabilities.
Type classes enable you to do things like this: