Last active
December 22, 2015 12:09
-
-
Save DeaconDesperado/6470529 to your computer and use it in GitHub Desktop.
A trivial Scala max priority queue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.heap; | |
import util.control.Breaks._; | |
import collection.mutable._; | |
abstract class Heap(){ | |
var table = ArrayBuffer[Char](); | |
var N:Int = -1; | |
def +=(value:Char) = { | |
N = N+1 | |
table+=value; | |
swim(N) | |
} | |
def swim(key:Int){ | |
var child = key+1 | |
while(child > 1 && comp(child/2,child)){ | |
var parent = child/2; | |
exch(parent, child); | |
child = parent | |
} | |
} | |
def exch(source:Int,target:Int){ | |
var a = source-1; | |
var b = target-1; | |
var tmp = table(a); | |
table.update(a,table(b)) | |
table.update(b,tmp) | |
} | |
def sink(key:Int){ | |
var parent = key + 1 | |
breakable{ | |
while(parent * 2 <= N){ | |
var child = parent * 2 | |
if(child < N && comp(parent,child+1)){ | |
child = child+1 | |
} | |
if(!comp(parent,child)){ | |
break | |
} | |
exch(parent,child) | |
parent = child; | |
} | |
} | |
} | |
def pop_max():Char = { | |
val ret = table(0) | |
exch(1,N+1) | |
table.remove(N) | |
N-=1 | |
sink(0) | |
ret | |
} | |
def comp(a:Int,b:Int):Boolean; | |
} | |
class MaxHeap extends Heap{ | |
override def comp(a:Int,b:Int):Boolean = { | |
val index_a = a-1 | |
val index_b = b-1 | |
val value_a = table(index_a) | |
val value_b = table(index_b) | |
value_a < value_b | |
} | |
} | |
class MinHeap extends Heap{ | |
override def comp(a:Int,b:Int):Boolean = { | |
val index_a = a-1 | |
val index_b = b-1 | |
val value_a = table(index_a) | |
val value_b = table(index_b) | |
value_a > value_b | |
} | |
} | |
object Heap { | |
def main(args: Array[String]) { | |
var h = new MinHeap(); | |
List('q','b','r','j','c','a','x').map((x)=> h+=x ) | |
println(h.table) | |
println(h.pop_max()) | |
println(h.pop_max()) | |
println(h.pop_max()) | |
println(h.pop_max()) | |
println(h.pop_max()) | |
println(h.pop_max()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment