欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JavaScript中三种常见的排序方法

程序员文章站 2023-01-10 12:41:58
1、快速排序:

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>

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