Advertisement
Guest User

Untitled

a guest
Dec 8th, 2014
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.63 KB | None | 0 0
  1. //OOP
  2.  
  3. def insertsort[T <% Ordered[T]](toSort: Array[T]): Array[T] = {
  4.  private def swap[T](i: Int, j: Int, array: Array[T]): Unit = {
  5.     val t = array(i)
  6.     array(i) = array(j)
  7.     array(j) = t
  8.   }
  9.     for (i <- 1 to toSort.length - 1) {
  10.       var j = i
  11.       while (j > 0 && toSort(j - 1) > toSort(j)) {
  12.         swap(j, j - 1, toSort)
  13.         j -= 1
  14.       }
  15.     }
  16.     toSort
  17. }
  18.  
  19. // Functional:
  20.  
  21.  def insertsort[T <% Ordered[T]](toSort: List[T]): List[T] = {
  22.     def insert[T <% Ordered[T]](list: List[T], el: T): List[T] = list.takeWhile(_ < el).:+(el).++(list.dropWhile(_ < el))
  23.     toSort./:(List[T]())(insert)
  24.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement