Sort an integer array: Difference between revisions

No edit summary
Line 1,405:
 
=={{header|Scala}}==
[[Category:Scala Implementations]]{{libheader|Scala}}
{{libheader|Scala}}
===Array===
Scala's "default" Array is a ''mutable'' data structure, very close to Java's Array. Generally speaking, that means an "array" is not very Scala-ishlesque, even as mutable data structures go. It can serves a purpose, though. If array is the right data type for your need, then that is how you sort it.<lang Scala>import scala.compat.Platform
<lang Scala>object Sort_an_integer_array extends App {
/** Function test the array if it is in order*/
def isSorted[N](arr: Array[N]) = array.sliding(2).forall(pair => pair(0) <= pair(1))
 
<lang Scala>object Sort_an_integer_array extends App {
val array = Array((for (i <- 0 to 10) yield scala.util.Random.nextInt(): _*):
_* /*Sequence is passed as multiple parameters to Array(xs : T*)*/)
 
/** Function test the array if it is in order */
def isSorted[NT](arr: Array[NT]) = array.sliding(2).forall(pair => pair(0) <= pair(1))
 
assert(!isSorted(array), "Not random")
scala.util.Sorting.quickSort(array)
assert(isSorted(array), "Not sorted")
 
println(s"Array in sorted order.\nSuccessfully completed without errors. [total ${Platform.currentTime - executionStart} ms]")
}</lang>
 
===List===
<lang Scala>println(List(5,2,78,2,578,-42).sorted)
Anonymous user