Skip to content

Instantly share code, notes, and snippets.

@ponkotuy
Last active August 9, 2016 07:47
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 ponkotuy/0a007d1d1bc1747ffeb6385c05b5c38a to your computer and use it in GitHub Desktop.
Save ponkotuy/0a007d1d1bc1747ffeb6385c05b5c38a to your computer and use it in GitHub Desktop.
挿入ソート
object InsertionSort {
def sort[A](ary: Array[A])(implicit ord: math.Ordering[A]): Unit = {
if(2 <= ary.length) {
ary.indices.tail.foreach { i =>
val j = (0 until i).indexWhere { j => ord.lt(ary(i), ary(j)) }
if(0 <= j) insert(ary, i, j)
println(ary.mkString("(", ", ", ")"))
}
}
}
def insert[A](ary: Array[A], from: Int, to: Int): Unit = {
val tmp = ary(from)
Range(from - 1, to - 1, -1).foreach { i =>
ary(i + 1) = ary(i)
}
ary(to) = tmp
}
}
object Main extends App {
val ary = Array(5, 2, 4, 6, 1, 3)
InsertionSort.sort(ary)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment