diff --git a/src/search/SelectionSearch.scala b/src/search/SelectionSearch.scala index 8216bcc..01aa4b2 100644 --- a/src/search/SelectionSearch.scala +++ b/src/search/SelectionSearch.scala @@ -10,11 +10,12 @@ */ def selectionsearch[A <% Ordered[A]](list: List[A], n: Int): Option[A] = { // quickselect - def search(t: (List[A], A, List[A]), m: Int): Option[A] = t match { - case (Nil, p, Nil) if m == 0 => Some(p) - case (Nil, _, Nil) => None - case (l, p, g) => select(l, p, g, l.length, m) - } + def search(t: (List[A], A, List[A]), m: Int): Option[A] = + t match { + case (Nil, p, Nil) if m == 0 => Some(p) + case (Nil, _, Nil) => None + case (l, p, g) => select(l, p, g, l.length, m) + } def select(l: List[A], p: A, g: List[A], q: Int, m: Int): Option[A] = if (m < q) partitionAndSearch(l, m) @@ -24,19 +25,18 @@ def selectionsearch[A <% Ordered[A]](list: List[A], n: Int): Option[A] = { // qu /** * The same as in quicksort. */ - def partition(as: List[A]): (List[A], A, List[A]) = { - def loop(p: A, as: List[A], l: List[A], g: List[A]): (List[A], A, List[A]) = - as match { - case h :: t => if (h < p) loop(p, t, h :: l, g) else loop(p, t, l, h :: g) - case Nil => (l, p, g) - } - loop(as.head, as.tail, Nil, Nil) - } + def loop(p: A, as: List[A], l: List[A], g: List[A]): (List[A], A, List[A]) = + as match { + case h :: t => if (h < p) loop(p, t, h :: l, g) else loop(p, t, l, h :: g) + case Nil => (l, p, g) + } def partitionAndSearch(as: List[A], m: Int): Option[A] = - if (as.isEmpty) None - else search(partition(as), m) + as match { + case h :: t => search(loop(h, t, Nil, Nil), m) + case Nil => None + } partitionAndSearch(list, n) }