Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions benchmarks/heap.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
$: << File.join(File.expand_path(File.dirname(__FILE__)), '../lib')
require 'algorithms'
include Algorithms

require 'rubygems'
require 'rbench'

TIMES = 10_000
ELEMENTS = []
TIMES.times { ELEMENTS << Random.rand('a'.ord .. 'z'.ord).chr }

RBench.run(2) do
%w(array heap).each { |s| self.send(:column, s.intern) }

report "Insertion then sort" do
heap = Containers::MinHeap.new
array = []

array do
TIMES.times do |x|
array << x
array.sort!
end
end

heap do
TIMES.times { |x| heap.push(x.ord, x) }
end
end

report "Swapping two elements" do
heap = Containers::MinHeap.new
ELEMENTS.each_with_index do |x, i|
heap.push(i, x)
end
array = ELEMENTS.sort

array do
10_000.times do
i = Random.rand(0..ELEMENTS.size-1)
j = Random.rand(0..ELEMENTS.size-1)
x = array[i]
y = array[j]
array[i] = y
array[j] = x
array.sort!
end
end

heap do
10_000.times do
i = Random.rand(0..ELEMENTS.size-1)
j = Random.rand(0..ELEMENTS.size-1)
x = heap.delete(i)
y = heap.delete(j)
heap.push(j, x)
heap.push(i, y)
end
end
end

report "Promoting one element" do
heap = Containers::MinHeap.new
ELEMENTS.each_with_index do |x, i|
heap.push(i, x)
end
array = ELEMENTS.sort

array do
10_000.times do
i = Random.rand(0..ELEMENTS.size-1)
j = Random.rand(0..i)
x = array[i]
array[j] = [x, array[j]]
array[i] = nil

array = array.flatten.compact.sort
end
end

heap do
10_000.times do
i = Random.rand(0..ELEMENTS.size-1)
j = Random.rand(0..i)
heap.change_key(i, j)
end
end
end
end
8 changes: 3 additions & 5 deletions lib/containers/heap.rb
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,10 @@ def push(key, value=key)
end
@size += 1

arr = []
w = @next.right
until w == @next do
arr << w.value
w = w.right
end
arr << @next.value
@stored[key] ||= []
@stored[key] << node
value
Expand Down Expand Up @@ -303,7 +300,8 @@ def delete(key)

# Node class used internally
class Node # :nodoc:
attr_accessor :parent, :child, :left, :right, :key, :value, :degree, :marked
attr_reader :value
attr_accessor :parent, :child, :left, :right, :key, :degree, :marked

def initialize(key, value)
@key = key
Expand Down Expand Up @@ -499,4 +497,4 @@ def min
def min!
self.pop
end
end
end