Skip to content

Commit 94242ac

Browse files
committed
循环队列 和 插入排序
1 parent 996974b commit 94242ac

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed

php/09_queue/Sequential.php

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
<?php
2+
3+
class LoopQueue
4+
{
5+
private $MaxSzie;
6+
private $data = [];
7+
private $head = 0;
8+
private $tail = 0;
9+
10+
/**
11+
* 初始化队列大小 最后的位置不存放数据,实际大小 = size++
12+
*/
13+
public function __construct($size = 10)
14+
{
15+
$this->MaxSzie = ++$size;
16+
}
17+
18+
/**
19+
* 队列满条件 ($this->tail+1) % $this->MaxSzie == $this->head
20+
*/
21+
public function enQueue($data)
22+
{
23+
if (($this->tail+1) % $this->MaxSzie == $this->head)
24+
return -1;
25+
26+
$this->data[$this->tail] = $data;
27+
$this->tail = (++$this->tail) % $this->MaxSzie;
28+
}
29+
30+
public function deQueue()
31+
{
32+
if ($this->head == $this->tail)
33+
return NULL;
34+
35+
$data = $this->data[$this->head];
36+
unset($this->data[$this->head]);
37+
$this->head = (++$this->head) % $this->MaxSzie;
38+
return $data;
39+
}
40+
41+
public function getLength()
42+
{
43+
return ($this->tail - $this->head + $this->MaxSzie) % $this->MaxSzie;
44+
}
45+
}
46+
47+
$queue = new LoopQueue(4);
48+
// var_dump($queue);
49+
$queue->enQueue(1);
50+
$queue->enQueue(2);
51+
$queue->enQueue(3);
52+
$queue->enQueue(4);
53+
// $queue->enQueue(5);
54+
var_dump($queue->getLength());
55+
$queue->deQueue();
56+
$queue->deQueue();
57+
$queue->deQueue();
58+
$queue->deQueue();
59+
$queue->deQueue();
60+
var_dump($queue);

php/11_sort/Sort.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?php
2+
3+
function insertSort(&$arr)
4+
{
5+
$i = 0;
6+
$len = count($arr);
7+
8+
while($i < $len){
9+
$data = $arr[$i+1];
10+
for ($j = $i;$j >=0 ;$j-- ){
11+
if ($data >= $arr[$j]){
12+
array_splice($arr, $i+1, 1);
13+
array_splice($arr, ++$j, 0, $data);
14+
break;
15+
}
16+
}
17+
18+
$i++;
19+
}
20+
}
21+
22+
$arr = [1,4,6,2,3,5,4];
23+
insertSort($arr);
24+
var_dump($arr);

0 commit comments

Comments
 (0)