Skip to content

Instantly share code, notes, and snippets.

@abishekk92
Created July 4, 2014 12:04
Show Gist options
  • Save abishekk92/fefd42a8692c52f19e26 to your computer and use it in GitHub Desktop.
Save abishekk92/fefd42a8692c52f19e26 to your computer and use it in GitHub Desktop.
Standard Sorting Algorithms implemented in Scala
import util.Random.shuffle
object Sort{
val toSort = List(1234, 23, 45, 56, 1)
def insert(list : List[Int], t : Int) : List[Int] = list match {
case Nil => List[Int](t)
case x :: xs if x > t => t :: x :: xs
case x :: xs => x :: insert(xs, t)
}
def sort(list : List[Int]) : List[Int] = {
list.foldLeft(List[Int]())((a,b) => insert(a,b))
}
def bubble(list : List[Int]) : List[Int] = list match {
case head :: List() => list
case head :: tail => {
val min = tail.min
val remaining = tail diff List(min)
if(head < min){
head :: min :: bubble(remaining)
}
else {
min :: bubble(head::remaining)
}
}
}
def quick(list : List[Int]) : List[Int] = list match {
case a if a.size < 2 => list
case _ => {
val (pivot::tail) = shuffle(list) take 1
val (more, less) = list.partition(_ > pivot)
quick(less) ++ quick(more)}
}
def mergeSort(xs : List[Int]) : List[Int] = {
val midpoint = xs.length/2
if(midpoint == 0) xs
else{
def merge(xs : List[Int], ys : List[Int]) : List[Int] = (xs, ys) match {
case (Nil, ys) => ys
case(xs, Nil) => xs
case(x :: xs1, y :: ys1) =>
if(x<y) x::merge(xs1,ys)
else y::merge(xs,ys1)
}
val (left, right) = xs splitAt midpoint
merge(mergeSort(left), mergeSort(right))
}
}
def main(args : Array[String]){
lazy val result = mergeSort(toSort)
lazy val result1 = quick(toSort)
lazy val result2 = bubble(toSort)
lazy val result3 = sort(toSort)
println(result)
println(result1)
println(result2)
println(result3)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment