求助:使用冒泡排序数组后文本框仅重复显示0的问题修复
Hey there! Let’s dig into why your bubble sort is spitting out nothing but zeros in the text box, even though your random number array works perfectly. Here are the most likely issues and how to fix them:
Common Culprit 1: You’re sorting a blank zero-filled array instead of your random numbers
It’s super easy to accidentally create a new array filled with zeros and sort that instead of copying your random values over. For example:
Wrong Code:
function bubbleSort(arr) { // Oops—this array starts as all zeros, never gets the random values! let sortedArr = new Array(arr.length).fill(0); for (let i = 0; i < sortedArr.length; i++) { for (let j = 0; j < sortedArr.length - i - 1; j++) { if (sortedArr[j] > sortedArr[j+1]) { let temp = sortedArr[j]; sortedArr[j] = sortedArr[j+1]; sortedArr[j+1] = temp; } } } return sortedArr; }
Fix:
First, copy your original random number array into the sorted array before sorting. You can use the spread operator ([...arr]) or Array.from(arr) to make a safe copy:
function bubbleSort(arr) { // Copy the original random array so we don't modify it accidentally let sortedArr = [...arr]; let n = sortedArr.length; for (let i = 0; i < n - 1; i++) { for (let j = 0; j < n - i - 1; j++) { if (sortedArr[j] > sortedArr[j + 1]) { // Swap the elements like normal let temp = sortedArr[j]; sortedArr[j] = sortedArr[j + 1]; sortedArr[j + 1] = temp; } } } return sortedArr; }
Common Culprit 2: Your display logic is only showing a single zero (not the whole array)
Even if your sorted array is correct, you might be accidentally repeating a zero in the text box because your loop to build the display string is broken.
Wrong Code:
function showSortedResult(sortedArr) { let output = ""; // This loop only runs once—if the first element is zero, you'll see it repeated // Or maybe you're hardcoding arr[0] instead of iterating all elements for (let i = 0; i < 1; i++) { output += sortedArr[0] + " "; } document.getElementById("sortedTextBox").value = output; }
Fix:
Use Array.join() to easily turn your sorted array into a string, or loop through every element properly:
function showSortedResult(sortedArr) { // Join all elements with spaces for clean output let output = sortedArr.join(" "); document.getElementById("sortedTextBox").value = output; }
Quick Troubleshooting Steps to Confirm
- Log the array before sorting: Add
console.log("Random array:", arr)at the start of your bubble sort function to make sure the random numbers are actually being passed in correctly. - Log the sorted array: Add
console.log("Sorted array:", sortedArr)right before returning from the sort function—if this is all zeros, the problem is in the sort logic. If it’s correct, the issue is in your display code. - Check for accidental resets: Make sure you’re not overwriting your array with zeros anywhere else in your code (like in a loop that incorrectly initializes values).
内容的提问来源于stack exchange,提问作者grootpoot

