Skip to content

Commit

Permalink
descending stack sort
Browse files Browse the repository at this point in the history
  • Loading branch information
doganoo committed Aug 20, 2018
1 parent 4534b6a commit 85d836f
Showing 1 changed file with 57 additions and 33 deletions.
90 changes: 57 additions & 33 deletions src/Datastructure/Stackqueue/Stack.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@

namespace doganoo\PHPAlgorithms\Datastructure\Stackqueue;

use doganoo\PHPAlgorithms\Common\Util\Comparator;


/**
* PHP implementation of a stack.
Expand All @@ -51,6 +53,8 @@
* @package StackQueue
*/
class Stack {
public const ASCENDING = 1;
public const DESCENDING = 2;
/**
* The stack is represented as an array. Note that a stack can also be implemented using a linked list.
*
Expand All @@ -59,45 +63,32 @@ class Stack {
private $stack = [];

/**
* push() adds an item to the stack.
* sorts the stack in descending order
*
* @param $item
* @return bool
* TODO add ascending order
*/
public function push($item): bool {
if (!$this->isValid()) {
return false;
public function sort(): void {
$r = new Stack();
while (!$r->isEmpty()) {
$tmp = $this->pop();

while ((!$r->isEmpty()) && (Comparator::lessThan($r->peek(), $tmp))) {
$this->push($r->pop());
}
$r->push($tmp);
}
while (!$r->isEmpty()) {
$this->push($r->pop());
}
/*
* using array_push is the better option since it
* takes the work of adding to the end.
*/
array_push($this->stack, $item);
return true;
}

/**
* checks if the stack element (the array) is null
* returns a boolean that determines if the stack is empty or not
*
* @return bool
*/
protected function isValid(): bool {
return $this->stack !== null;
}

/**
* peek() returns the element 'on top' of the stack
*
*/
public function peek() {
if (null === $this->stack) {
return null;
}
if (0 === $this->stackSize()) {
return null;
}
$value = $this->stack[$this->stackSize() - 1];
return $value;
public function isEmpty(): bool {
return $this->stackSize() === 0;
}

/**
Expand Down Expand Up @@ -131,11 +122,44 @@ public function pop() {
}

/**
* returns a boolean that determines if the stack is empty or not
* peek() returns the element 'on top' of the stack
*
*/
public function peek() {
if (null === $this->stack) {
return null;
}
if (0 === $this->stackSize()) {
return null;
}
$value = $this->stack[$this->stackSize() - 1];
return $value;
}

/**
* push() adds an item to the stack.
*
* @param $item
* @return bool
*/
public function isEmpty(): bool {
return $this->stackSize() === 0;
public function push($item): bool {
if (!$this->isValid()) {
return false;
}
/*
* using array_push is the better option since it
* takes the work of adding to the end.
*/
array_push($this->stack, $item);
return true;
}

/**
* checks if the stack element (the array) is null
*
* @return bool
*/
protected function isValid(): bool {
return $this->stack !== null;
}
}

0 comments on commit 85d836f

Please sign in to comment.