Search code examples
javascriptbubble-sort

BubbleSort algorithm in JavaScript


So I was trying to practice JS and decided to go for bubble sort algorithm. I wrote the code below and realized that it doesn't work when there's a 3 digit number in the array. I run the code in Chrome's console. Can anyone tell me what the problem is?

var array = [];

var length = prompt("Please enter length of array: ");

for (count = 0; count < length; count++) {
  array.push(prompt("Enter a number: "));
}

for (i = 0; i < length; i++) {
  for (j = 0; j < length - i - 1; j++) {
    if (array[j] > array[j + 1]) {
      var temp = array[j];
      array[j] = array[j + 1];
      array[j + 1] = temp;
    }
  }
}

console.log("Your list of numbers is sorted!" + array);

Solution

  • The Window.prompt function returns a string, so you should convert it to number with Number (else < would compare them alphabetically), e.g.

    var arr = [];
    var len = parseInt(prompt("Please enter length of array: "));
    for (count = 0; count < len; count++) {
      arr.push(Number(prompt("Enter a number: ")));
    }
    for (let i = 0; i < len; i++) {
      for (let j = 0; j < len - i - 1; j++) {
        if (arr[j] > arr[j + 1]) {
          let tmp = arr[j];
          arr[j] = arr[j + 1];
          arr[j + 1] = tmp;
        }
      }
    }
    console.log("Your list of numbers is sorted: " + arr);