1.实现阶乘(递归)
function factorialize(num) {
if (num < 0) {
return -1;
} else if (num === 0 || num === 1) {
return 1;
} else {
return (num * factorialize(num - 1));
}
}
factorialize(5);
2.找出下列正数组的最大差值
输入 [10,5,11,7,8,9] 输出 6
function getMaxProfit(arr) {
var minPrice = arr[0];
var maxProfit = 0;
for (var i = 0; i < arr.length; i++) {
var currentPrice = arr[i];
minPrice = Math.min(minPrice, currentPrice);
var potentialProfit = currentPrice - minPrice;
maxProfit = Math.max(maxProfit, potentialProfit);
}
return maxProfit;
}
3.截断字符串
function truncate(str, num) {
if(num>=str.length) return str;
if(num<=3) return str.slice(0,num)+"...";
if(str.length>num) return str.slice(0,num-3)+"...";
}
truncate("Absolutely Longer", 2);
4.排序sort
var arr = [222,1,55,10,22];
arr.sort(function(a, b){return a-b;})
5.冒泡排序算法
function sortarr(arr){
for(i=0;i<arr.length-1;i++){
for(j=0;j<arr.length-1-i;j++){
if(arr[j]>arr[j+1]){
var temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
return arr;
}
sortarr([5,5,8,9,54,7,7,4,5,2,1,20,3,2,5,6,9,9,10])
6.选择排序法
function selectionSort(arr) {
var len = arr.length;
var minIndex, temp;
console.time("选择排序耗时");
for (var i = 0; i < len - 1; i++) {
minIndex = i;
for (var j = i + 1; j < len; j++) {
if (arr[j] < arr[minIndex]) { //寻找最小的数
minIndex = j; //将最小数的索引保存
}
}
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
console.timeEnd("选择排序耗时");
return arr;
}