数据结构与算法
第一章 内容
数据结构:
- 链表
- 栈
- 队列
- 树
- 图
- 哈希
- 堆
算法:
- 排序
- 插入排序
- 希尔排序
- 冒泡排序
- 快速排序
- 选择排序
- 堆排序
- 归并排序
- 基数排序
- 查找
- 顺序查找
- 折半查找
- 分块查找
- 二叉树查找
- 哈希查找
- 子串搜索
- Boyer-Moore算法
- Horspool算法
- Sunday算法
- KMP算法
- KR算法
- AC自动机
算法技巧:
- 贪婪
- 分治
- 动态规划
- 随机化
- 回溯
第2章 常用排序
$arr = array(
17,
6,
5,
9,
8
);
/*2
5
6
9
8*/
//冒泡排序
function maopao($arr) {
for($i=1;$len=count($arr); $i<$len; $i++) {
for($j=$i-1; $j>=0; $j--) {
if($arr[$i] < $arr[$j]) {
$tmp = $arr[$i];
$arr[$i] = $arr[$j];
$arr[$j] = $tmp;
} else {
break;
}
}
}
return $arr;
}
function cp($arr) {
for($i=1,$len=count($arr); $i<$len; $i++) {
if( $arr[$i] < $arr[$i-1] ) {
$j = $i-1;
$tmp = $arr[$i];
while($j>=0 && $tmp < $arr[$j]) {
$arr[$j+1] = $arr[$j];
$j-=1;
}
$arr[$j+1] = $tmp;
}
}
return $arr;
}
print_r(cp($arr));
// 希尔排序
for($step = floor(count($arr)/2) ; $step>=1; $step = floor($step/2)) {
for($i=$step;$i<count($arr);$i++) {
$tmp = $arr[$i];
for($j=$i;$j>=$step;$j-=$step) {
if($tmp < $arr[$j-$step]) {
$arr[$j] = $arr[$j-$step];
} else {
break;
}
}
$arr[$j] = $tmp;
}
}
二叉树
http://blog.devtang.com/blog/2015/06/16/talk-about-tech-interview/
class Node {
protected $value = null;
protected $left = null;
protected $right = null;
public function insert($value) {
if($this->value === null) {
$this->value = $value;
} else if($value <= $this->value) {
if($this->left === null) {
$this->left =new self();
$this->left->insert($value);
} else {
$this->left->insert($value);
}
} else if($value > $this->value) {
if($this->right === null) {
$this->right =new self();
$this->right->insert($value);
} else {
$this->right->insert($value);
}
}
}
}
$tree = new Node();
$tree->insert(4);
$tree->insert(2);
$tree->insert(1);
$tree->insert(3);
$tree->insert(6);
$tree->insert(5);
$tree->insert(7);
print_r($tree);
// 遍历
function bianli($tree) {
if($tree->left!==null) {
bianli($tree->left);
}
echo $tree->value , '<br />';
if($tree->right!==null) {
bianli($tree->right);
}
}
bianli($tree);
//反转二叉树
function revTree($tree) {
if($tree->left !== null) {
$tree->left = revTree($tree->left);
}
if($tree->right !== null) {
$tree->right = revTree($tree->right);
}
$tmp = $tree->left;
$tree->left = $tree->right;
$tree->right = $tmp;
return $tree;
}
print_r( revTree($tree) );