您的位置:首页 > Web前端 > JavaScript

几种经典排序js实现------冒泡排序/选择排序/快速排序/直接插入排序

2018-01-09 00:00 417 查看
摘要: 为下一站做准备,加油。

冒泡排序

原理

比较相邻的元素。如果第一个比第二个大,就交换他们两个。

对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。

针对所有的元素重复以上的步骤,除了最后一个。

持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>冒泡排序</title>

<script type="text/javascript">
Array.prototype.bubbleSort = function(){
var len = this.length;
if(this == null || this.length == 0){
return;
}
let temp;
while(len>0){
for(var i=0; i<len; i++){
if(this[i]>this[i+1]){
temp = this[i];
this[i] = this[i+1];
this[i+1] = temp;
}
}
len--;
}

return this;
}

var arr = [3, 1, 2, 10, 9, 50];
console.log(arr.bubbleSort());
</script>

</head>
<body>

</body>
</html>

快速排序

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>快速排序</title>

<script type="text/javascript">
Array.prototype.quickSort = function() {
console.log(this);
if((this == null) || (this.length == 0)){
return;
}
var temp;
// i从0开始递增
for(var i=0;i<this.length; i++){
// j从arr.length-1开始递减
for(var j = this.length-1; j>=i; j--){
// 从右边开始找比其小的数,找到即交换位置
if(this[j] < this[i]){
temp = this[i];
this[i] = this[j];
this[j] = temp;
}
}
}
return this;
};

var arr = [3, 1, 100, 10, 9, 50];
console.log(arr.quickSort());
</script>

</head>
<body>

</body>
</html>

选择排序

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>选择排序</title>

<script type="text/javascript">
Array.prototype.selectSort = function() {
console.log(this);
if((this == null) || (this.length == 0)){
return;
}
var minIndex;
var temp;
for(var i=0; i<this.length; i++) {
minIndex=i;//无序区的最小数据数组下标
for(var j=i+1; j<this.length; j++) {
//在无序区中找到最小数据并保存其数组下标
if(this[minIndex]>this[j]) {
minIndex=j;
console.log(minIndex)
}
}
if(minIndex != i) {
//如果不是无序区的最小值位置,不是默认的第一个数据,则交换之。
temp = this[i];
this[i] = this[minIndex];
this [minIndex] = temp;
}
}
return this;
}

var arr = [3, 1, 2, 10, 9, 50];
console.log(arr.selectSort());

</script>

</head>
<body>

</body>
</html>

直接插入排序

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>直接插入排序</title>

<script type="text/javascript">

Array.prototype.straightInsertSort = function () {
console.log(this);
if((this == null) || (this.length == 0)){
return;
}
//第0位独自作为有序数列,从第1位开始向后遍历
for(var i=1; i<this.length; i++) {
//0~i-1位为有序,若第i位小于i-1位,继续寻位并插入,否则认为0~i位也是有序的,忽略此次循环,相当于continue
if(this[i] < this[i-1]) {
var temp = this[i];//保存第i位的值
var k = i - 1;
//从第i-1位向前遍历并移位,直至找到小于第i位值停止
for(var j=k; j>=0 && temp<this[j]; j--) {
this[j+1] = this[j];
k--;
}
this[k+1] = temp;//插入第i位的值
}
}
return this;
};

var arr = [3, 1, 2, 10, 9, 50];
console.log(arr.straightInsertSort());
</script>

</head>
<body>

</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: