Advertisement
Guest User

Untitled

a guest
Aug 16th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. package examples
  2.  
  3. /** Quick sort, imperative style */
  4. object sort {
  5.  
  6. /** Nested methods can use and even update everything
  7. * visible in their scope (including local variables or
  8. * arguments of enclosing methods).
  9. */
  10. def sort(a: Array[Int]) {
  11.  
  12. def swap(i: Int, j: Int) {
  13. val t = a(i); a(i) = a(j); a(j) = t
  14. }
  15.  
  16. def sort1(l: Int, r: Int) {
  17. val pivot = a((l + r) / 2)
  18. var i = l
  19. var j = r
  20. while (i <= j) {
  21. while (a(i) < pivot) i += 1
  22. while (a(j) > pivot) j -= 1
  23. if (i <= j) {
  24. swap(i, j)
  25. i += 1
  26. j -= 1
  27. }
  28. }
  29. if (l < j) sort1(l, j)
  30. if (j < r) sort1(i, r)
  31. }
  32.  
  33. if (a.length > 0)
  34. sort1(0, a.length - 1)
  35. }
  36.  
  37. def println(ar: Array[Int]) {
  38. def print1 = {
  39. def iter(i: Int): String =
  40. ar(i) + (if (i < ar.length-1) "," + iter(i+1) else "")
  41. if (ar.length == 0) "" else iter(0)
  42. }
  43. Console.println("[" + print1 + "]")
  44. }
  45.  
  46. def main(args: Array[String]) {
  47. val ar = Array(6, 2, 8, 5, 1)
  48. println(ar)
  49. sort(ar)
  50. println(ar)
  51. }
  52.  
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement