一、冒泡排序

冒泡排序

1
2
3
4
5
6
7
8
9
10
11
12
13
function bubbleSort(arr) {
var len = arr.length;
for(var i = 0; i < len - 1; i++) {
for(var j = 0; j < len - 1 - i; j++) {
if(arr[j] > arr[j+1]) { // 相邻元素两两对比
var temp = arr[j+1]; // 元素交换
arr[j+1] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}

二、快速排序

快速排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function quickSort(arr, left, right) {
var len = arr.length,
partitionIndex,
left = typeof(left) !='number' ? 0 : left,
right = typeof(right) !='number' ? len - 1 : right;

if(left < right) {
partitionIndex = partition(arr, left, right);
quickSort(arr, left, partitionIndex-1);
quickSort(arr, partitionIndex+1, right);
}
return arr;
}

function partition(arr, left ,right) { // 分区操作
var pivot = left, // 设定基准值(pivot)
index = pivot + 1;
for(var i = index; i <= right; i++) {
if(arr[i] < arr[pivot]) {
swap(arr, i, index);
index++;
}
}
swap(arr, pivot, index - 1);
return index-1;
}

function swap(arr, i, j) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

三、24点算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?PHP

class TwentyFourCal {
public $needle = 24;
public $precision = '1e-6';

function TwentyFourCal() {
}

private function notice($mesg) {
var_dump($mesg);
}

/**
* 取得用户输入方法
*/
public function calculate($operants = array()) {
try {
$this->search($operants,4);
} catch (Exception $e) {
$this->notice($e->getMessage());
return;
}
$this->notice('can\'t compute!');
return;
}

/**
* 求24点算法PHP实现
*/
private function search($expressions,$level) {
if ($level == 1) {
$result = 'return ' . $expressions[0] . ';';
if ( abs(eval($result) - $this->needle) <= $this->precision) {
throw new Exception($expressions[0]);
}
}
for ($i=0;$i<$level;$i++) {
for ($j=$i+1;$j<$level;$j++) {
$expLeft = $expressions[$i];
$expRight = $expressions[$j];
$expressions[$j] = $expressions[$level - 1];

$expressions[$i] = '(' . $expLeft . ' + ' . $expRight . ')';
$this->search($expressions,$level - 1);

$expressions[$i] = '(' . $expLeft . ' * ' . $expRight . ')';
$this->search($expressions,$level - 1);

$expressions[$i] = '(' . $expLeft . ' - ' . $expRight . ')';
$this->search($expressions,$level - 1);

$expressions[$i] = '(' . $expRight . ' - ' . $expLeft . ')';
$this->search($expressions,$level - 1);

if ($expLeft != 0) {
$expressions[$i] = '(' . $expRight . ' / ' . $expLeft . ')';
$this->search($expressions,$level - 1);
}

if ($expRight != 0) {
$expressions[$i] = '(' . $expLeft . ' / ' . $expRight . ')';
$this->search($expressions,$level - 1);
}
$expressions[$i] = $expLeft;
$expressions[$j] = $expRight;
}
}
return false;
}

function __destruct() {
}
}