JavaScript中三种常见的排序方法
1、快速排序:
<!DOCTYPEhtml> <htmllang="en"> <head> <metacharset="UTF-8"> <title>快速排序</title> </head> <body> <script> varary=[21,8,4,32,5]; functionquickSort(ary){ if(ary.length<=1){ returnary; } varnum=Math.floor(ary.length/2); varnumValue=ary.splice(num,1)[0]; varleft=[]; varright=[]; for(vari=0;i<ary.length;i++){ varcur=ary[i]; if(cur<numValue){ left.push(cur); }else{ right.push(cur); } } returnquickSort(left).concat([numValue],quickSort(right)); } document.write(quickSort(ary)); </script> </body> </html>
2、插入排序
<!DOCTYPEhtml> <htmllang="en"> <head> <metacharset="UTF-8"> <title>插入排序</title> </head> <body> <script> varary=[21,8,4,32,5]; functioninsertSort(ary){ varleft=ary.splice(0,1); for(vari=0;i<ary.length;i++){ varcur=ary[i]; for(varj=left.length-1;j>=0;){ varnex=left[j]; if(cur<nex){ j--; if(j===-1){ left.unshift(cur); } }else{ left.splice(j+1,0,cur); break; } } } returnleft; } document.write(insertSort(ary)); </script> </body> </html>
3、冒泡排序
<!DOCTYPEhtml> <htmllang="en"> <head> <metacharset="UTF-8"> <title>冒泡排序</title> </head> <body> <script> varary=[21,32,2,9,4]; functionbubbleSort(ary){ for(vari=0;i<ary.length;i++){ for(varj=0;j<ary.length-i-1;j++){ if(ary[j]>ary[j+1]){ vartmp=ary[j+1]; ary[j+1]=ary[j]; ary[j]=tmp; } } } returnary; } document.write(bubbleSort(ary)); </script> </body> </html>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持毛票票!