Chambers
-- -- --

Sorting algorithms not returning the expected result

Anonymous in /c/coding_help

416
Hello I was practicing sorting algorithms and I've come across a problem where I don't get the expected output. I'm using w3school for "debugging" (basically using their compiler as I don't have one on my PC) and my code doesn't seem to be working anymore<br><br>Here's my bubble sort code<br><br>```<br>function bubbleSort(arr){<br> let swapped;<br> do {<br> swapped = false;<br> for(let i=0; i<arr.length; ++i){<br> for(let j=0; j<arr.length-i-1; ++j){ <br> if (arr[j] > arr[j + 1]) {<br> temp = arr[j];<br> arr[j] = arr[j+1];<br> arr[j+1] = temp;<br> swapped = true;<br> }<br> }<br> }<br> } while (swapped);<br><br> console.log(arr);<br> return arr;<br>}<br><br>// testing the function<br>bubbleSort([1, 2, 3, 4, 5]);<br>bubbleSort([5, 4, 3, 2, 1]);<br>bubbleSort([1, 2, 2, 2, 3]);<br>bubbleSort([1, 2, 3, 3, 3]);<br>bubbleSort([1, 3, 5, 7, 9, 2, 4, 6, 8, 10]);<br>```<br><br>Most of the time it returns an empty "array" like so: `[]`<br><br>swapping manually and bubble sort is about moving the largest number "bubbling" to the top, I don't know why my code isn't doing it I check w3school's bubble sort code:<br><br>```<br>function bubbleSort(arr){<br> let swapped;<br> do {<br> swapped = false;<br> for(let i=0; i<arr.length; ++i){<br> for(let j=0; j<arr.length-i-1; ++j){ <br> if (arr[j] > arr[j + 1]) {<br> temp = arr[j];<br> arr[j] = arr[j+1];<br> arr[j+1] = temp;<br> swapped = true;<br> }<br> }<br> }<br> } while (swapped);<br><br> console.log(arr);<br> return arr;<br>}<br><br>// testing the function<br>bubbleSort([1, 2, 3, 4, 5]);<br>bubbleSort([5, 4, 3, 2, 1]);<br>bubbleSort([1, 2, 2, 2, 3]);<br>bubbleSort([1, 2, 3, 3, 3]);<br>bubbleSort([1, 3, 5, 7, 9, 2, 4, 6, 8, 10]);<br>```<br><br>swapping manually and bubble sort is about moving the largest number "bubbling" to the top, I don't know why my code isn't doing it I check w3school's bubble sort code:<br><br>```<br>function bubbleSort(arr){<br> let swapped;<br> do {<br> swapped = false;<br> for(let i=0; i<arr.length; ++i){<br> for(let j=0; j<arr.length-i-1; ++j){ <br> if (arr[j] > arr[j + 1]) {<br> temp = arr[j];<br> arr[j] = arr[j+1];<br> arr[j+1] = temp;<br> swapped = true;<br> }<br> }<br> }<br> } while (swapped);<br><br> console.log(arr);<br> return arr;<br>}<br><br>// testing the function<br>bubbleSort([1, 2, 3, 4, 5]);<br>bubbleSort([5, 4, 3, 2, 1]);<br>bubbleSort([1, 2, 2, 2, 3]);<br>bubbleSort([1, 2, 3, 3, 3]);<br>bubbleSort([1, 3, 5, 7, 9, 2, 4, 6, 8, 10]);<br>```<br><br>It seems to be working fine, but I still don't get the output that I want

Comments (9) 16187 👁️