Advertisement
Guest User

Untitled

a guest
Sep 21st, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. package object quickSelect {
  2. // (Pseudo)random number generator with a fixed seed so that
  3. // error situations can be reproduced easier
  4. val rand = new scala.util.Random(21)
  5.  
  6. /**
  7. * Find the k:th smallest (0 for the smallest) element in
  8. * the integer sequence seq by using the quickselect algorithm.
  9. */
  10. def find(seq: Seq[Int], k: Int): Int = {
  11. require(0 <= k && k < seq.length)
  12. // Make a working copy of the sequence as we cannot modify the argument sequence
  13. val a: Array[Int] = seq.toArray
  14.  
  15. def swap ( a : Array[Int], i:Int, j:Int): Unit = {
  16. val t = a(i); a(i) = a(j); a(j) = t
  17. }
  18.  
  19. def partition(a:Array[Int], lo: Int, hi: Int): (Int, Int) = {
  20. val random = lo + rand.nextInt(hi - lo)
  21. var pivot = a(random)
  22. swap(a, lo, random)
  23. var i = lo + 1
  24. var lt = lo
  25. var gt = hi
  26. while(i <= gt){
  27. if(a(i) < pivot) {
  28. swap(a, lt, i)
  29. lt = lt + 1
  30. i = i + 1
  31. }else if(a(i) > pivot){
  32. swap(a, i, gt)
  33. gt = gt - 1
  34. }else i = i + 1
  35. }
  36. (gt, lt)
  37. }
  38.  
  39. def select(a: Array[Int], left: Int, right: Int, k: Int): Int = {
  40. var lo = left
  41. var hi = right
  42. while(lo <= hi){
  43. if(lo == hi) return a(lo)
  44. val pvtIndx = partition(a, lo, hi)
  45. if(k > pvtIndx._1) lo = pvtIndx._1 + 1
  46. else if(k < pvtIndx._2) hi = pvtIndx._2 - 1
  47. else return a(pvtIndx._2)
  48. }
  49. return -1 //code never reaches here
  50. }
  51.  
  52. return select(a, 0, a.length - 1, k)
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement