我正在建立一个网站,它制作一个随机的数字串列,并通过可视化对其进行快速排序。当我在我的 HTML 档案的脚本部分中运行该函式时,它无法正常作业,但是当我将它作为 js 档案运行时它作业正常。这有什么原因吗?快速排序功能在底部。
<!DOCTYPE html>
<html>
<H1>
Representation
</H1>
<h2></h2>
<body>
<button id='Quick Sort' onclick="quicksort()">Quick Sort</button>
<canvas id="myCanvas" width="1400" height="650" style="border:1px solid #2a1baf;"></canvas>
<input type="range" min="4" max="1000" value="1" class="slider" id="slider">
<p>Amount of Rectangles: <span id="choice"></span></p>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var setup = true;
var slider = document.getElementById("slider");
var slideText = document.getElementById("choice");
var size = 4;
slideText.innerHTML = size;
if (setup) {
var arr = reset(size);
setup = false;
}
var button = document.getElementById('Quick Sort');
slider.oninput = function() {
slideText.innerHTML = this.value;
size = this.value;
ctx.clearRect(0, 0, c.width, c.height);
arr = reset(size);
}
function reset(size) {
nums = [];
ar = [];
for (i = 1; i <= size; i ) {
nums.push(i);
}
while (nums.length > 0) {
const random = Math.floor(Math.random() * nums.length);
ar.push(nums[random]);
nums.splice(random, 1);
}
ctx.beginPath();
for (var i = 0; i < size; i ) {
ctx.rect(i * (1400 / size), 0, 1400 / size, 600 / (size) * ar[i]);
}
ctx.stroke();
return ar;
}
function bin_search(arr, val, start, end) {
if (start == end) {
if (arr[start] > val) {
return start;
}
else {
return start 1;
}
}
if (start > end) {
return start;
}
var mid = Math.floor((start end) / 2);
if (arr[mid] < val) {
return bin_search(arr, val, mid 1, end);
}
else if (arr[mid] > val) {
return bin_search(arr, val, start, mid - 1);
}
else {
return mid;
}
}
function quicksort() {
for (var i = 1; i < arr.length; i ) {
val = arr[i];
j = bin_search(arr, val, 0, i - 1);
slice2 = arr.slice(j, i);
slice3 = arr.slice(i 1);
arr = arr.slice(0, j);
arr.push(val);
arr = arr.concat(slice2);
arr = arr.concat(slice3);
ctx.beginPath();
for (var i = 0; i < size; i ) {
ctx.rect(i * (1400 / size), 0, 1400 / size, 600 / (size) * ar[i]);
}
ctx.stroke();
}
}
</script>
</body>
</html>
uj5u.com热心网友回复:
您的问题是由于 var 宣告 - 使用 let for for 回圈可以解决您的问题
喜欢:
function quicksort() {
for (let i = 1; i < arr.length; i ) {
val = arr[i];
j = bin_search(arr, val, 0, i - 1);
slice2 = arr.slice(j, i);
slice3 = arr.slice(i 1);
arr = arr.slice(0, j);
arr.push(val);
arr = arr.concat(slice2);
arr = arr.concat(slice3);
ctx.beginPath();
for (let i = 0; i < size; i ) {
ctx.rect(i * (1400 / size), 0, 1400 / size, 600 / (size) * ar[i]);
}
ctx.stroke();
}
}
我不会评论许多变量缺少它们的宣告
0 评论