Last active
August 9, 2016 07:47
-
-
Save ponkotuy/0a007d1d1bc1747ffeb6385c05b5c38a to your computer and use it in GitHub Desktop.
挿入ソート
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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