JavaScript中三种常见的排序方法
(编辑:jimmy 日期: 2024/11/17 浏览:3 次 )
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>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!
下一篇:Angular2 Service实现简单音乐播放器服务