Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //OOP
- def insertsort[T <% Ordered[T]](toSort: Array[T]): Array[T] = {
- private def swap[T](i: Int, j: Int, array: Array[T]): Unit = {
- val t = array(i)
- array(i) = array(j)
- array(j) = t
- }
- for (i <- 1 to toSort.length - 1) {
- var j = i
- while (j > 0 && toSort(j - 1) > toSort(j)) {
- swap(j, j - 1, toSort)
- j -= 1
- }
- }
- toSort
- }
- // Functional:
- def insertsort[T <% Ordered[T]](toSort: List[T]): List[T] = {
- def insert[T <% Ordered[T]](list: List[T], el: T): List[T] = list.takeWhile(_ < el).:+(el).++(list.dropWhile(_ < el))
- toSort./:(List[T]())(insert)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement