快速排序
var quicky=function(arr){
if(arr.length <=1){
return arr;
}
var mun=Math.floor(arr.length/2);
var mounk=arr.splice(mun,1)[0];
var left=[];
var right=[];
for(var i=0;i<arr.length;i++){
if(arr[i]<mounk){
left.push(arr[i]);
}else{
right.push(arr[i]);
}
}
return quicky(left).concat([mounk],quicky(right));
};
冒泡排序
function bubbleSort(arr){
for(var i=0; i<arr.length; i++){
for(var j=0; j<=arr.length; j++){
var temp = 0;
if(arr[j] > arr[j+1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}
删除数组中重复元素
var arr1=[1,3,2,2,4,5,4,6,7,6,6];
var arr2=[];
for (var i=0,len=arr1.length;i<len;i++){
if(arr2.indexOf(arr1[i])<0){
arr2.push(arr1[i]);
}
}
数组中最大差值
function getMaxProfit(arr){
var min = arr[0],
max = arr[0];
for(var i = 0; i < arr.length; i++){
if(arr[i] < min) min = arr[i];
if(arr[i] > max) max = arr[i];
}
return max - min;
}
判断回文字符串
function palindrome(str){
var re = /[\W_]/g;
var lowRegStr = str.toLowerCase().replace(re,'');
if(lowRegStr.length===0) return true;
if(lowRegStr[0]!=lowRegStr[lowRegStr.length-1]) return false;
return palindrome(lowRegStr.slice(1,lowRegStr.length-1));
}
翻转字符串
function reverseString(str){
var tmp = '';
for(var i=str.length-1; i>=0; i--)
tmp += str[i];
return tmp
}
指定长度随机字符串
function randomString(n){
var str = 'abcdefghijklmnopqrstuvwxyz0123456789';
var tmp = '';
for(var i=0; i<n; i++) {
tmp += str.charAt(Math.round(Math.random()*str.length));
}
return tmp;
}
统计字符串中字母个数或统计最多字母数
var str = "ewwefdddddhhhhll";
var obj = {};
for(var i=0;i<str.length;i++){
var v = str.charAt(i);
if(obj[v] && obj[v].value == v){
obj[v].count = ++ obj[v].count;
}else{
obj[v] = {};
obj[v].count = 1;
obj[v].value = v;
}
}
for(key in obj){
console.log(obj[key].value +'='+obj[key].count);
}
斐波那契数列
function getfib(n){
if(n == 0) return 0;
if(n == 1) return 1;
if(n > 1) return getfib(n-1) + getfib(n-2);
}
function fibo(len){
var fibo = [];
for(var i = 0; i < len; i++){
fibo.push(getfib(i));
}
return fibo;
}
二分查找
var towSelect=function(arr,low,high,key){
if(low>high){
return -1;
}
var mid=parseInt((high+low)/2);
if(arr[mid]==key){
return mid;
}else if(arr[mid]>key){
high=mid-1;
return towSelect(arr,low,high,key);
}else if(arr[mid]<key){
low=mid+1;
return towSelect(arr,low,high,key);
}
};