Advertisement
Guest User

Heap NE RADI

a guest
Mar 31st, 2015
237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.58 KB | None | 0 0
  1. class Heap[Item: Manifest](maxsize: Int, less: (Item,Item) => Boolean) {
  2.  
  3.       private var curr: Int = 1
  4.      
  5.       def getSize(): Int = curr-1
  6.      
  7.       val arr = new Array[Item](maxsize+1)
  8.      
  9.       def insert(newItem: Item): Unit = {
  10.         arr(curr) = newItem
  11.         fixInsertion(curr)
  12.         curr += 1
  13.         //println(arr.dropRight(arr.length - curr).mkString(","))
  14.       }
  15.      
  16.       def += (newItem: Item): Unit = {
  17.         insert(newItem)
  18.       }
  19.      
  20.      
  21.       def top(remove: Boolean = true): Item =  {
  22.         if(!remove)
  23.           return arr(1)
  24.         curr -= 1
  25.         swap(1, curr)
  26.         fixRemoval(1)
  27.         //println(arr.drop(1).dropRight(arr.length - curr).mkString(","))
  28.         arr(curr)
  29.       }
  30.      
  31.       def remove(item: Item, i: Int = 1): Unit = {
  32.         if (i < curr) {
  33.           if (arr(i) == item) {
  34.             curr -= 1
  35.             swap(i, curr)
  36.             fixRemoval(i)
  37.           }
  38.           else
  39.             remove(item, i+1)
  40.         }
  41.         else
  42.           throw new NoSuchElementException("Element not found")
  43.       }
  44.      
  45.       def isEmpty: Boolean =  {
  46.         curr == 1
  47.       }
  48.      
  49.       private def fixInsertion(i: Int): Unit = {
  50.         if (i > 1 && less(arr(i),arr(i/2))) {
  51.           swap(i, i/2)
  52.           fixInsertion(i/2)
  53.         }
  54.       }
  55.    
  56.       private def fixRemoval(i: Int): Unit = {
  57.         if (i * 2 < curr) {
  58.             val next = if (i*2 < curr-1) { if (less(arr(i*2), arr(i*2+1))) i*2 else i*2+1} else i*2
  59.             if (less(arr(next), arr(i))) {
  60.                 swap(i, next)
  61.                 fixRemoval(next)
  62.             }
  63.         }
  64.       }
  65.      
  66.       private def swap(a: Int, b: Int): Unit = {
  67.          val swap = arr(b)
  68.         arr(b) = arr(a)
  69.         arr(a) = swap
  70.       }
  71.    
  72.    
  73.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement