【发布时间】:2021-03-24 07:25:28
【问题描述】:
我正在尝试修改 this solution 以适用于冒泡排序,但我有点超出我的深度,尤其是对于整个 async function 业务。该代码在一定程度上可以工作,但并未遵循我对冒泡排序所期望的确切模式,并且仅对数组进行了部分排序。
谁能帮帮我?
let values = [];
let startSort = true;
function bubbleSort( a ) {
// create copy of the array
clone = a.slice();
// asynchronous sort the copy
recursiveBubbleSort( clone, clone.length );
return;
}
//Recursive Bubble Sort
async function recursiveBubbleSort( arr, n ) {
//If there is only single element
//the return the array
if ( n === 1 ) {
return arr;
}
await recursiveBubbleSort( arr, n - 1 );
//Swap the elements by comparing them
for ( let j = 0; j < n - 1; j++ ) {
if ( arr[j] > arr[j + 1] ) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
// copy back the current state of the sorting
values = arr.slice();
// slow down
await sleep( 500 );
}
async function sleep( ms ) {
return new Promise( resolve => setTimeout( resolve, ms ) );
}
function setup() {
createCanvas( 600, 190 );
frameRate( 60 );
}
let numOfRects = 15;
let rectWidth;
function draw() {
if ( startSort ) {
startSort = false;
rectWidth = floor( width / numOfRects );
values = new Array( floor( width / rectWidth ) );
for ( let i = 0; i < values.length; i++ ) {
values[i] = random( height );
}
bubbleSort( values );
}
background( 23 );
stroke( 0 );
fill( 255 );
for ( let i = 0; i < values.length; i++ ) {
rect( i * rectWidth, height - values[i], rectWidth, values[i] );
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.min.js"></script>
【问题讨论】:
-
谢谢,但我的问题中引用了该答案。
标签: algorithm visualization p5.js bubble-sort