Posted in Javascript onFebruary 24, 2017
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>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持三水点靠木!
JavaScript中三种常见的排序方法
- Author -
前端工程师_钱成声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@