Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- " Heap class to implement priority queue "
- Object subclass: Heap [
- | arr end |
- Heap class >> new: size [
- ^super new init: size
- ]
- init: size [
- arr := Array new: size.
- end := 0.
- ^self
- ]
- isEmpty [ ^(end = 0) ]
- notEmpty [ ^(end ~= 0) ]
- heapify: idx [
- | left right smallest |
- left := 2 * idx.
- right := 2 * idx + 1.
- smallest := idx.
- ((left <= end) and: [(arr at: idx) > (arr at: left)]) ifTrue: [
- smallest := left
- ].
- ((right <= end) and: [(arr at: smallest) > (arr at: right)]) ifTrue: [
- smallest := right
- ].
- (smallest ~= idx) ifTrue: [
- arr swap: idx with: smallest.
- self heapify: smallest.
- ]
- ]
- insert: item [
- | i parent |
- end := end + 1.
- (end > arr size) ifTrue: [
- stderr nextPutAll: ('Heap size (%1) exceeded!' % {arr size}); nl.
- Error signal.
- ].
- arr at: end put: item.
- i := end.
- [(i ~= 1) and: [(arr at: (parent := i // 2)) > (arr at: i)]] whileTrue: [
- arr swap: i with: parent.
- i := parent.
- ].
- ^item
- ]
- next [
- | top |
- (end = 0) ifTrue: [ ^nil ].
- top := arr at: 1.
- end := end - 1.
- (end > 0) ifTrue: [
- arr at: 1 put: (arr at: end + 1).
- self heapify: 1.
- ].
- ^top
- ]
- priority [
- (end = 0) ifTrue: [ ^nil ].
- ^(arr at: 1) priority
- ]
- ]
- "
- | PriorityQueue implementation using Heap
- "
- Object subclass: PriorityItem [
- | priority data |
- PriorityItem class >> new: pri data: anArray [ ^super new init: pri data: anArray ]
- init: pri data: array [ priority := pri. data := array. ^self ]
- > state [ ^priority > state priority ]
- priority [ ^priority ]
- data [ ^data ]
- ]
- Object subclass: PriorityQueue [
- | heap |
- PriorityQueue class >> new [ ^super new init ]
- init [ heap := Heap new: 100000. ^self ]
- isEmpty [ ^heap isEmpty ]
- notEmpty [ ^heap notEmpty ]
- at: pri insert: data [ heap insert: (PriorityItem new: pri data: data) ]
- next [ ^heap next data ]
- priority [ ^heap priority ]
- ]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement