Skip to content

Instantly share code, notes, and snippets.

@TechZi
Created June 27, 2010 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TechZi/454719 to your computer and use it in GitHub Desktop.
Save TechZi/454719 to your computer and use it in GitHub Desktop.
<?php
class Link {
public $value;
public $next;
public function __construct($value) {
$this->value = $value;
}
public function displayLink() {
echo $this->value.' ';
}
}
class SortedList {
private $first;
public function __construct($array) {
$this->first = null;
for ($i = 0; $i < count($array); $i++) {
$this->insert($array[$i]);
}
}
public function isEmpty() {
return empty($this->first);
}
public function insert($value) {
$link = new Link($value);
$current = $this->first;
$previous = null;
while ($current != null && $current->value < $value) {
$previous = $current;
$current = $current->next;
}
if ($previous == null) {
$this->first = $link;
} else {
$previous->next = $link;
}
$link->next = $current;
}
public function remove() {
$temp = $this->first;
$this->first = $temp->next;
return $temp;
}
}
$arr = array();
$size = 10;
for ($i = 0; $i < $size; $i++) {
$arr[$i] = rand(1, 100);
echo $arr[$i].' ';
}
echo "\n";
echo '<br />';
$list = new SortedList($arr);
for ($i = 0; $i < $size; $i++) {
$arr[$i] = $list->remove();
}
for ($i = 0; $i < $size; $i++) {
echo $arr[$i]->value.' ';
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment