0

im new in this forum so, if i wrong to post this i apologize. Im learnin Javascript and for training i made this bubblesort algorithm:

var x = [1, 5, 2, 8, 3, 6, 4, 9, 7]; 

sort(x);

function sort(params) {
  var appoggio=0;
  for (i=0; i<params.length; i++) {
    for (j=0; j<params.length; j++) {
        appoggio=params[j];
        params[j] = params[j+1];
        params[j+1] = appoggio;
    }
  }
}

console.log(x); 

I have made a basic html page where i call this script but it doesn't work and i don't understand why. I try to debugg it inser some alert(params[j]) inside the for cycle but after the first interation the scrpt blocks all the web page. What i have to do?

  • You're adding elements to the array while looping over it. This will result in an infinite loop. An easy fix would be to store the array length in a variable. – Reyno Dec 14 '20 at 09:01
  • Also, not the cause of your error, but you should declare `i` and `j` using `let` inside the for loop condition or they will become global variables. As in `for (let i=0; ...` – Keldan Chapman Dec 14 '20 at 09:02
  • _"I try to debugg it inser some alert(params[j]) inside the for cycle but after the first interation the scrpt blocks all the web page."_ Use a real debugger. Most browsers provide tools to debug and analyze your code, e.g. you can open DevTools with Ctrl+Shift+I – Thomas Sablik Dec 14 '20 at 09:20

2 Answers2

2

You are falling in an infinite loop as you push at j+1 even when you hit the end of your list (which increment the length each time). Try to stop at params.length-1.

MetallimaX
  • 594
  • 4
  • 13
  • 2
    This is not the main problem with OP code. There is no logic! – Eloims Dec 14 '20 at 09:09
  • thank you for your answer! I completely forgot about the condition because of the distraction XD the real problem is that I never realized I was going out of the array. Now I understand what I was doing wrong. Thanks again :) – Paolo Bardi Dec 14 '20 at 09:23
1

The if condition is missing!

You need to swap values only if they are not ordered correctly.

Plus, as @MetallimaX said, you need to stop your loop at params.length - 1 to avoid writing outside of the array

Without giving you the answer, which would spoil everything:

for a given number of times (enough that values can bubble all the way) {
    for each adjacent values pair (from left to right) {
         if the pair is not ordered correctly {
              swap both elements()
         }
    }
}
Eloims
  • 4,927
  • 4
  • 23
  • 39