-2

I wanna ascend this array below. [1, 2,3,5, 3, 2, 4,] to [1,2,2,3,3,4,5]

but my code below didn't back correctly answer. Could someone teach me how to sort array of numbers using javascript?

    var arr = [1, 2,3,5, 3, 2, 4,];

for (var i = 0; i < arr.length - 1; i++){
    var left = arr[i];
    var right = arr[i + 1];
    if (left > right) {
        arr[i + 1] = left;
        arr[i] = right;
    } 

}
console.log(arr);
2
  • 1
    looks like a single iteration of bubblesort (incorrect one) Commented Jun 12, 2020 at 6:00
  • 1
    you can use this [1, 2,3,5, 3, 2, 4].sort() Commented Jun 12, 2020 at 6:02

1 Answer 1

1

Here is bubble sort algorithm using only for-loop and while

const arr = [1, 2, 3, 5, 3, 2, 4];

let is_sorted = false;

while (!is_sorted) {
  is_sorted = true;
  for (let i = 1; i < arr.length; i++) {
    if (arr[i - 1] > arr[i]) {
      // swap
      const temp = arr[i - 1];
      arr[i - 1] = arr[i];
      arr[i] = temp;
      is_sorted = false;
    }
  }
}

console.log(arr);

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much your answer! I don't have any ideas to use while-loop! Thanks!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.