源代码:
function CreateArray(length) {
var array1 = [];
for (var k = 0, t = length; k < t; k++) {
array1.push(Math.round(Math.random() * 3000000))
};
return array1;
var array = CreateArray(100,500,1000) // works only for 100
console.time("insertionSort")
function insertionSort(array) {
var countOuter = 0;
var countInner = 0;
var countSwap = 0;
for(var i = 0; i < array.length; i++) {
countOuter++;
var temp = array[i];
var j = i - 1;
while (j >= 0 && array[j] > temp) {
countInner++;
countSwap++;
array[j + 1] = array[j];
j--;
}
array[j + 1] = temp;
}
console.log('outer:', countOuter, 'inner:', countInner, 'swap:', countSwap);
return array;
}
console.timeEnd("insertionSort")
insertionSort(array.slice());
最后一次打电话我要检查100,500,1000,5000和其他不同的长度。有什么想法吗?
我希望最后一次调用适用于任何长度的数组。
答案 0 :(得分:3)
您需要CreateArray
一次创建多个数组,然后您需要insertionSort
能够一次处理多个数组 - 或者甚至更好地调用另一个函数(一次)为每个数组调用insertionSort
:
const CreateArray = (...lengths) => lengths.map(length => (
Array.from({ length }, () => Math.floor(Math.random() * 3000000))
));
function insertionSort(array) {
var countOuter = 0;
var countInner = 0;
var countSwap = 0;
for (var i = 0; i < array.length; i++) {
countOuter++;
var temp = array[i];
var j = i - 1;
while (j >= 0 && array[j] > temp) {
countInner++;
countSwap++;
array[j + 1] = array[j];
j--;
}
array[j + 1] = temp;
}
console.log('outer:', countOuter, 'inner:', countInner, 'swap:', countSwap);
}
const insertionSortMultipleArrays = (arrs) => {
arrs.forEach(arr => {
console.time("insertionSort");
insertionSort(arr);
console.timeEnd("insertionSort");
});
};
const arrays = CreateArray(100,500,1000,5000);
insertionSortMultipleArrays(arrays);
&#13;