我目前正在为我的扩展论文进行调查。我正在测试合并算法和快速排序算法之间的比较。我的结果出现这个怪异的异常。我的第二个for循环中的每个第一个排序返回的时间都比其余时间长得多。我不知道为什么,有人可以解释吗?
由于某种原因,JSFiddle将不会输出任何内容,尽管在本地运行时它可以正常工作。所以,我将代码发布在这里:
function generateRandomArray(l, min, max) {
var a = [];
for (var i = 0; i < l; i++) {
a.push(Math.ceil(Math.random() * max + min - 1));
}
return a;
}
function quickSort(a) {
var less = [],
pivotList = [],
greater = [];
if (a.length <= 1) return a;
var pivot = a[0];
for (var i = 0; i < a.length; i++) {
if (a[i] < pivot) less.push(a[i]);
else if (a[i] > pivot) greater.push(a[i]);
else pivotList.push(a[i]);
}
less = quickSort(less);
greater = quickSort(greater);
return less.concat(pivotList, greater);
}
function mergeSort(left, right) {
if (!left) return right;
if (!right) return left;
var result = [],
leftIndex = 0,
rightIndex = 0;
while (leftIndex < left.length & rightIndex < right.length) {
if (left[leftIndex] <= right[rightIndex]) {
result.push(left[leftIndex]);
leftIndex++;
} else {
result.push(right[rightIndex]);
rightIndex++;
}
}
if (leftIndex != left.length) {
var temp = left.slice(leftIndex, left.length);
result = result.concat(temp);
} else if (rightIndex != right.length) {
var temp = right.slice(rightIndex, right.length);
result = result.concat(temp);
}
return result;
}
function mergeSortSplit(a) {
if (a.length <= 1) return a;
var middle = Math.floor(a.length / 2);
var left = a.slice(0, middle),
right = a.slice(middle, a.length);
left = mergeSortSplit(left);
right = mergeSortSplit(right);
return mergeSort(left, right);
}
window.onload = function() {
var timeResults = [
[[], [], [], [], []],
[[], [], [], [], []]
];
for (var i = 0; i < 10; i++) {
for (var j = 3; j < 6; j++) {
var array = generateRandomArray(Math.pow(10, j), 1, 100);
var mergeSortTime = window.performance.now();
mergeSortSplit(array);
timeResults[0][j - 3].push(window.performance.now() - mergeSortTime);
var quickSortTime = window.performance.now();
quickSort(array);
timeResults[1][j - 3].push(window.performance.now() - quickSortTime);
}
}
for (var i = 0; i < timeResults.length; i++) {
document.getElementById("demo").innerHTML += "<b>" + (i + 1) + ". </b><br>";
for (var j = 0; j < timeResults[i].length; j++) {
document.getElementById("demo").innerHTML += "<b>" + Math.pow(10, j + 3) + ": </b>";
for (k = 0; k < timeResults[i][j].length; k++) {
document.getElementById("demo").innerHTML += timeResults[i][j][k] + "<b> | </b>";
}
document.getElementById("demo").innerHTML += "<br><br>";
}
document.getElementById("demo").innerHTML += "<br><br><br>";
}
console.log(timeResults);
}
<html>
<head>
<meta charset="utf-8">
<title>EE Investigation</title>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<p id="demo"></p>
</body>
</html>