JavaScript中三种常见的排序方法

网络编程 2021-07-04 19:20www.168986.cn编程入门
本篇文章主要介绍了JavaScript中三种常见的排序方法快速排序、插入排序、冒泡排序,具有很好的参考价值,狼蚁网站SEO优化跟着长沙网络推广一起来看下吧

1、快速排序

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>快速排序</title>
</head>
<body>
<script>
 var ary=[21,8,4,32,5];
 function quickSort(ary){
 if(ary.length<=1){
  return ary;
 }
 var num=Math.floor(ary.length/2);
 var numValue=ary.splice(num,1)[0];
 var left=[];
 var right=[];
 for(var i=0; i<ary.length; i++){
  var cur=ary[i];
  if(cur<numValue){
  left.push(cur);
  }else{
  right.push(cur);
  }
 }
 return quickSort(left).concat([numValue],quickSort(right));
 }
 document.write(quickSort(ary));
</script>
</body>
</html>

2、插入排序

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>插入排序</title>
</head>
<body>
<script>
 var ary=[21,8,4,32,5];
 function insertSort(ary){
 var left=ary.splice(0,1);
 for(var i=0; i<ary.length; i++){
  var cur=ary[i];
  for(var j=left.length-1; j>=0;){
  var nex=left[j];
  if(cur<nex){
   j--;
   if(j===-1){
   left.unshift(cur);
   }
  }else{
   left.splice(j+1,0,cur);
   break;
  }
  }
 }
 return left;
 }
 document.write(insertSort(ary));
</script>
</body>
</html>

3、冒泡排序

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>冒泡排序</title>
</head>
<body>
<script>
 var ary=[21,32,2,9,4];
 function bubbleSort(ary){
 for(var i=0; i<ary.length; i++){
  for(var j=0; j<ary.length-i-1; j++){
  if(ary[j]>ary[j+1]){
   var tmp=ary[j+1];
   ary[j+1]=ary[j];
   ary[j]=tmp;
  }
  }
 }
 return ary;
 }
 document.write(bubbleSort(ary));
</script>
</body>
</html>

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望多多支持狼蚁SEO!

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by