数组去重
function unique(arr) { var result = {},newArr = []; for(var i=0;i<arr.length;i++){ if(!result[arr[i]]){ newArr.push(arr[i]); result[arr[i]]=1; } } return newArr; }
插入排序---直接插入排序,时间算法复杂度O (n^2)
function insertSort(a) { for(var i= 1; i<a.length; i++){ if(a[i] < a[i-1]){ var j= i-1; var x = a[i]; a[i] = a[i-1]; while(x < a[j]){ a[j+1] = a[j]; j--; } a[j+1] = x; } } console.log(a) }
冒泡排序---时间复杂度O(n^2)
function bubbleSort( a ,n){ for(var i =0 ; i< n-1; ++i) { for(var j = 0; j < n-i-1; ++j) { if(a[j] > a[j+1]) { var tmp = a[j] ; a[j] = a[j+1] ; a[j+1] = tmp; } } } console.log(a) }
两个有序数组合并为一个有序数组(两种方法都可以)
function mergeList(a,b) { var c= [],i=0,j=0,k=0; while(i<a.length && j< b.length){ if(a[i]<=b[j]){ c.push(a[i]); i++; }else{ c.push(b[j]); j++; } } while(i<a.length){ c.push(a[i]); i++; } while(j<a.length){ c.push(b[j]); j++; } return c; }
function merge(left, right) { var tmp = []; while (left.length && right.length) { if (left[0] < right[0]) tmp.push(left.shift()); else tmp.push(right.shift()); } return tmp.concat(left, right); }