常用的经典算法 js程序
包括:冒泡、选择、插入和快速算法的js实现。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>相关算法实现</title> </head> <body> <p>jiayou</p> </body> <script type="text/javascript"> window.onload = function(){ // 冒泡算法 function rangemao(str){ var len= str.length; for(var i=0;i<len-1;i++){ for(var j=0;j<len-1-i;j++){ if(str[j]>str[j+1]){ var temp = str[j]; str[j]=str[j+1]; str[j+1] = temp; } } } return str; } // 选择算法 function rangexuan(str){ var mindex,temp; var len = str.length; for(var i=0;i<len-1;i++){ mindex = i; for(var j=i+1;j<len;j++){ if(str[j]<str[mindex]){ mindex = j; } } temp = str[i]; str[i]=str[mindex]; str[mindex] = temp; } return str; } // 插入算法 function rangein(str){ var len = str.length; var preindex,current; for(var i=1;i<len;i++){ current = str[i]; preindex = i-1; while(preindex >= 0 && str[preindex]>current){ str[preindex+1] = str[preindex]; preindex--; } str[preindex+1] = current; } return str; } // 快速算法 function rangeQuick(str) { if(str.length<=1){ return str; } var mid = Math.floor(str.length/2); var midValue = str.splice(mid,1); var left = []; var right = []; for (var i=0; i<str.length;i++){ if(str[i]<midValue){ left.push(str[i]); }else { right.push(str[i]); } } return arguments.callee(left).concat(midValue,arguments.callee(right)); } var arr = ["1","3","s","2","9"]; alert(rangemao(arr)); alert(rangexuan(arr)); alert(rangein(arr)); alert(rangeQuick(arr)); } </script> </html>