Skip to content

Instantly share code, notes, and snippets.

@evandrix
Created July 7, 2011 00:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evandrix/1068643 to your computer and use it in GitHub Desktop.
Save evandrix/1068643 to your computer and use it in GitHub Desktop.
Scala by Example
def sqrt(x: Double): Double = sqrtIter(1.0, x)
def sqrtIter(guess: Double, x: Double): Double =
if (isGoodEnough(guess, x)) guess
else sqrtIter(improve(guess, x), x)
def improve(guess: Double, x: Double) =
(guess + x / guess) / 2
def isGoodEnough(guess: Double, x: Double) =
abs(square(guess) - x) < 0.001
object QuickSort extends App {
def sort(xs: Array[Int]): Array[Int] = {
if (xs.length <= 1) xs
else {
val pivot = xs(xs.length / 2)
Array.concat(
sort(xs filter (pivot >)),
xs filter (pivot ==),
sort(xs filter (pivot <)))
}
}
println(sort (Array[Int](5,4,3,2,1)).deep.mkString(" "))
}
object QuickSort extends App {
def sort(xs: Array[Int]):Array[Int] = {
def swap(i: Int, j: Int) {
val t = xs(i); xs(i) = xs(j); xs(j) = t
}
def sort1(l: Int, r: Int) {
val pivot = xs((l + r) / 2)
var i = l; var j = r
while (i <= j) {
while (xs(i) < pivot) i += 1
while (xs(j) > pivot) j -= 1
if (i <= j) {
swap(i, j)
i += 1
j -= 1
}
}
if (l < j) sort1(l, j)
if (j < r) sort1(i, r)
}
sort1(0, xs.length - 1)
return xs
}
println(sort (Array[Int](5,4,3,2,1)).deep.mkString(" "))
}
@evandrix
Copy link
Author

evandrix commented Jul 8, 2011

quicksort.scala:
$ scalac qsort.scala
$ scala QuickSort
1 2 3 4 5
$

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment