Skip to content

Instantly share code, notes, and snippets.

@alherd-by
Last active March 23, 2016 10:28
Show Gist options
  • Save alherd-by/83d8d8a46e2c80db7c44 to your computer and use it in GitHub Desktop.
Save alherd-by/83d8d8a46e2c80db7c44 to your computer and use it in GitHub Desktop.
<?php
class HastTable implements ArrayAccess
{
private $storage = [];
private $hashFunc;
public function __construct(callable $hashFunction)
{
$this->hashFunc = $hashFunction;
}
public function __debugInfo()
{
return [
'values' => json_encode(array_values($this->storage)),
json_encode($this->storage)
];
}
public function offsetExists($offset)
{
}
public function offsetGet($offset)
{
$key = call_user_func($this->hashFunc, $offset);
return $this->storage[$key];
}
public function selectionSort()
{
$haystack = array_values($this->storage);
$size = count($haystack);
for ($i = 0; $i < $size - 1; $i++) {
$min = $i;
for ($j = $i + 1; $j < $size; $j++) {
if ($haystack[$j] < $haystack[$min]) {
$min = $j;
}
}
$temp = $haystack[$i];
$haystack[$i] = $haystack[$min];
$haystack[$min] = $temp;
}
$this->storage = array_combine(array_keys($this->storage), $haystack);
}
public function bucketSort()
{
$data = array_values($this->storage);
$minValue = $data[0];
$maxValue = $data[0];
$dataLength = count($data);
for ($i = 1; $i < $dataLength; $i++) {
if ($data[$i] > $maxValue) {
$maxValue = $data[$i];
}
if ($data[$i] < $minValue) {
$minValue = $data[$i];
}
}
$bucket = [];
$bucketLength = $maxValue - $minValue + 1;
for ($i = 0; $i < $bucketLength; $i++) {
$bucket[$i] = [];
}
for ($i = 0; $i < $dataLength; $i++) {
array_push($bucket[$data[$i] - $minValue], $data[$i]);
}
$k = 0;
for ($i = 0; $i < $bucketLength; $i++) {
$bucketCount = count($bucket[$i]);
if ($bucketCount > 0) {
for ($j = 0; $j < $bucketCount; $j++) {
$data[$k] = $bucket[$i][$j];
$k++;
}
}
}
$this->storage = array_combine(array_keys($this->storage), $data);
}
public function toArray() : array
{
return $this->storage;
}
public function offsetSet($offset, $value)
{
$key = call_user_func($this->hashFunc, $offset);
$this->storage[$key] = $value;
}
public function offsetUnset($offset)
{
unset($this->storage[$offset]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment