sample.scala.txt 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package examples
  2. /** Quick sort, imperative style */
  3. object sort {
  4. /** Nested methods can use and even update everything
  5. * visible in their scope (including local variables or
  6. * arguments of enclosing methods).
  7. */
  8. def sort(a: Array[Int]) {
  9. def swap(i: Int, j: Int) {
  10. val t = a(i); a(i) = a(j); a(j) = t
  11. }
  12. def sort1(l: Int, r: Int) {
  13. val pivot = a((l + r) / 2)
  14. var i = l
  15. var j = r
  16. while (i <= j) {
  17. while (a(i) < pivot) i += 1
  18. while (a(j) > pivot) j -= 1
  19. if (i <= j) {
  20. swap(i, j)
  21. i += 1
  22. j -= 1
  23. }
  24. }
  25. if (l < j) sort1(l, j)
  26. if (j < r) sort1(i, r)
  27. }
  28. if (a.length > 0)
  29. sort1(0, a.length - 1)
  30. }
  31. def println(ar: Array[Int]) {
  32. def print1 = {
  33. def iter(i: Int): String =
  34. ar(i) + (if (i < ar.length-1) "," + iter(i+1) else "")
  35. if (ar.length == 0) "" else iter(0)
  36. }
  37. Console.println("[" + print1 + "]")
  38. }
  39. def main(args: Array[String]) {
  40. val ar = Array(6, 2, 8, 5, 1)
  41. println(ar)
  42. sort(ar)
  43. println(ar)
  44. }
  45. }