tonglin0325的个人主页

JavaScript排序算法——快速排序

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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>快速排序</title>
<!--<link rel="stylesheet" type="text/css" href="../style/fdt.css" />-->
<script type="text/javascript" src="../js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="../js/jquery.easydrag.handler.beta2.js"></script>
<script type="text/javascript">

$(document).ready(
function() {

var array_1 = [4,5,3,1,2];
alert(array_1);
/*quickSort*/
alert(quickSort(array_1));

}
);



</script>

<style type="text/css">

* { padding:0; margin:0; }

body {
padding: 100px;
font-size: 15px;
}




</style>


<script type="text/javascript">
function quickSort(array){
//var array = [8,4,6,2,7,9,3,5,74,5];
//var array = [0,1,2,44,4,324,5,65,6,6,34,4,5,6,2,43,5,6,62,43,5,1,4,51,56,76,7,7,2,1,45,4,6,7];
var i = 0;
var j = array.length - 1;
var Sort = function(i, j){

// 结束条件
if(i == j ){ return };

var key = array[i];
var stepi = i; // 记录开始位置
var stepj = j; // 记录结束位置

while(j > i){
alert(array);
// j <<-------------- 向前查找
if(array[j] >= key){
j--;
}else{
array[i] = array[j]
//i++ ------------>>向后查找
while(j > ++i){
if(array[i] > key){
array[j] = array[i];
break;
}
}
}
}

alert(array);
alert("i="+i+",j="+j+",stepi="+stepi+",stepj="+stepj);

// 如果第一个取出的 key 是最小的数
if(stepi == i){
Sort(++i, stepj);
return ;
}

// 最后一个空位留给 key
array[i] = key;

// 递归
Sort(stepi, i);
Sort(j, stepj);
}

Sort(i, j);

return array;
}


</script>


</head>




<body>
快速排序
</body>
</html>