Skip to content

Commit

Permalink
循环队列 和 插入排序
Browse files Browse the repository at this point in the history
  • Loading branch information
SeasClouds committed Oct 15, 2018
1 parent 996974b commit 94242ac
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 0 deletions.
60 changes: 60 additions & 0 deletions php/09_queue/Sequential.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

class LoopQueue
{
private $MaxSzie;
private $data = [];
private $head = 0;
private $tail = 0;

/**
* 初始化队列大小 最后的位置不存放数据,实际大小 = size++
*/
public function __construct($size = 10)
{
$this->MaxSzie = ++$size;
}

/**
* 队列满条件 ($this->tail+1) % $this->MaxSzie == $this->head
*/
public function enQueue($data)
{
if (($this->tail+1) % $this->MaxSzie == $this->head)
return -1;

$this->data[$this->tail] = $data;
$this->tail = (++$this->tail) % $this->MaxSzie;
}

public function deQueue()
{
if ($this->head == $this->tail)
return NULL;

$data = $this->data[$this->head];
unset($this->data[$this->head]);
$this->head = (++$this->head) % $this->MaxSzie;
return $data;
}

public function getLength()
{
return ($this->tail - $this->head + $this->MaxSzie) % $this->MaxSzie;
}
}

$queue = new LoopQueue(4);
// var_dump($queue);
$queue->enQueue(1);
$queue->enQueue(2);
$queue->enQueue(3);
$queue->enQueue(4);
// $queue->enQueue(5);
var_dump($queue->getLength());
$queue->deQueue();
$queue->deQueue();
$queue->deQueue();
$queue->deQueue();
$queue->deQueue();
var_dump($queue);
24 changes: 24 additions & 0 deletions php/11_sort/Sort.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

function insertSort(&$arr)
{
$i = 0;
$len = count($arr);

while($i < $len){
$data = $arr[$i+1];
for ($j = $i;$j >=0 ;$j-- ){
if ($data >= $arr[$j]){
array_splice($arr, $i+1, 1);
array_splice($arr, ++$j, 0, $data);
break;
}
}

$i++;
}
}

$arr = [1,4,6,2,3,5,4];
insertSort($arr);
var_dump($arr);

0 comments on commit 94242ac

Please sign in to comment.