常用的两种排序方法
//利用sort方法进行排序 var arr = new Array(6) arr[0] = "10" arr[1] = "5" arr[2] = "40" arr[3] = "25" arr[4] = "100" arr[5] = "1" var arr1 = [12, 14, 15, 2, 4, 5, 214, 53, 75, 34] function fn(array) { return array.sort(function(a, b) { return a - b; }) } console.log(fn(arr1)) // 冒泡排序 function fn1(array) { var i = 0, len = array.length, j, d; for (; i < len; i++) { for (j = 0; j < len; j++) { if (array[i] < array[j]) { d = array[j]; array[j] = array[i]; array[i] = d; } } } return array; } console.log(fn1(arr1))
//线性搜索(入门HelloWorld) //A为数组,x为要搜索的值 function linearSearch(A, x) { for (var i = 0; i < A.length; i++) { if (A[i] == x) { return i; } } return -1; } //二分搜索 //A为已按"升序排列"的数组,x为要查询的元素 //返回目标元素的下标 function binarySearch(A, x) { var low = 0, high = A.length - 1; while (low <= high) { var mid = Math.floor((low + high) / 2); //下取整 if (x == A[mid]) { return mid; } if (x < A[mid]) { high = mid - 1; } else { low = mid + 1; } } return -1; } //选择排序 数据规模越小越好 //思路:找到最小值的下标记下来,再交换 function selectionSort(arr) { var len = arr.length; var minIndex, temp; 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; } return arr; } //插入排序 //假定当前元素之前的元素已经排好序,先把自己的位置空出来, //然后前面比自己大的元素依次向后移,直到空出一个"坑", //然后把目标元素插入"坑"中 function insertionSort(arr) { var len = arr.length; var preIndex, current; for (var i = 1; i < len; i++) { preIndex = i - 1; current = arr[i]; while(preIndex >= 0 && arr[preIndex] > current) { arr[preIndex+1] = arr[preIndex]; preIndex--; } arr[preIndex+1] = current; } return arr; } //字符串反转(比如:ABC -> CBA) function inverse(s) { var arr = s.split(''); var i = 0, j = arr.length - 1; while (i < j) { var t = arr[i]; arr[i] = arr[j]; arr[j] = t; i++; j--; } return arr.join(''); } //js递归常见算法 阶乘 function fact(num) { if (num <= 1) { return 1; } else { return num * arguments.callee(num - 1); //此处更改了。 } } var anotherFact = fact; fact = null; alert(anotherFact(4)); //结果为24.
//更换对象的key值 var arr = ['e','f','g']; var obj = {a:1,b:2,c:3} var keyArr=[]; for(var key in obj){ keyArr.push(key); } arr.map(function(value,index,key){ obj[value] = obj[keyArr[index]]; delete obj[keyArr[index]] }); console.log(obj);
/*数组去重 根据对象的key值唯一性*/ var arr = [2,4,8,2,4]; var obj = {},i = 0; for(; i < arr.length; i++){/*数组先转换为obj对象*/ obj[arr[i]] = true; } console.log(obj); var newArr = []; for(var item in arr){/*遍历数组的属性 并判断是否是对象的key值 如果是就push到新数组*/ if(obj.hasOwnProperty(item)){ newArr.push(item); } } console.log(newArr);