K. Shah - 1 year ago 161

Javascript Question

I have made a bubble sort algorithm (sorta) using JS. It works sometimes, but the problem is that it only iterates through the array once. Here is my code:

`function bubble(arr) {`

for (var i = 0; i < arr.length; i++) {

if (arr[i] > arr[i + 1]) {

var a = arr[i]

var b = arr[i + 1]

arr[i] = b

arr[i + 1] = a

}

}

return arr;

}

Answer Source

You could add a Boolean variable to show when its been swapped such:

```
function bubbleSort(a)
{
var swapped;
do {
swapped = false;
for (var i=0; i < a.length-1; i++) {
if (a[i] > a[i+1]) {
var temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
swapped = true;
}
}
} while (swapped);
}
```

This would be how I implement the **Bubble Sort** algorithm, you could also use two for loops, something like this:

```
function bubbleSort(theArray) {
var i, j;
for (i = theArray.length ā 1; i >= 0; iā) {
for (j = 0; j <= i; j++) {
if (theArray[j + 1] < theArray[j]) {
var temp = theArray[j];
theArray[j] = theArray[j + 1];
theArray[j + 1] = temp;
}
}
}
return theArray;
```

**Edit:**
To understand what the second loop does you need to understand the bubble sort algorithm, here's a really good start. Also I'd recommend actually visualising the algorithm so check out that link also