function insertSrot(arr){ if (arr == null || arr.length < 2) { return 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; } function insertSrot1(arr) { window.count1 = 0; if (arr == null || arr.length < 2) { return arr; } var len = arr.length; for (var i = 1; i < len; i++) { for(var j = i-1;j>=0;j--){ window.count1++; if(arr[j+1]<arr[j]){ var temp = arr[j+1]; arr[j+1] = arr[j]; arr[j] = temp; } } } console.log('未使用二分优化的计算次数',window.count1) return arr; } //2分查找 function binary_search(arr, key) { var low = 0, high = arr.length - 1; while (low <= high) { window.count++; var mid = parseInt((high + low) / 2); if (key == arr[mid]) { return mid; } else if (key > arr[mid]) { low = mid + 1; } else if (key < arr[mid]) { high = mid - 1; } if (key > arr[mid] && key < arr[mid + 1]) { return mid; }else if(key<arr[0]){ return -1; }else if(key>arr[high]){ return high; } } }; // console.error(binary_search([2,12], 13)) // console.error(binary_search([2, 12], 1)) // console.error(binary_search([2,12], 12)) console.error(binary_search([2], 1)) // console.error(binary_search([1,2,5,11,12,17,21,29,333,1110,3222],999)) //插入排序优化,即将比较改为二分查找 function insertSrot2(arr) { if (arr == null || arr.length < 2) { return arr; } var len = arr.length; window.count = 0; for (var i = 1; i < len; i++) { let ind = binary_search(arr.slice(0,i),arr[i]); // console.log('ind', ind) // console.log('arr[i]', arr[i]) // console.log('arr', arr.slice(0, i)) let current = arr[i]; for (let j = i-1; j >= ind; j--) { window.count++; arr[j + 1] = arr[j]; } if (ind < 0) { arr[0] = current } else{ arr[ind+1] = current; } } console.log('优化后的计算次数',count) return arr; } let arr1 = [12,2,31,21,245,21,2,4,5,332,788,09,980] let arr2 = [12,2] // console.log(window.insertSrot(arr1)) // console.log(window.insertSrot1(arr1)) // console.log(window.insertSrot2([12,2,31])) console.log(window.insertSrot2(arr1))
这次主要对插入排序的查找使用了二分查找进行优化,对比优化前后的次数,发现还是很有效果的~