Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
挿入ソート
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
You can’t perform that action at this time.