Let’s say the following is our unsorted array with negative and positive numbers −
var arr = [10, -22, 54, 3, 4, 45, 6];
Example
Following is the code to implement Bubble Sort −
function bubbleSort(numberArray, size) { for (var lastIndex = size - 1; lastIndex > 0; lastIndex--) { for (var i = 0; i < lastIndex; i++) { if (numberArray[i] > numberArray[i + 1]) { var temp = numberArray[i]; numberArray[i] = numberArray[i + 1]; numberArray[i + 1] = temp; } } } return numberArray; } var arr = [10, -22, 54, 3, 4, 45, 6]; console.log(bubbleSort(arr, arr.length));
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo280.js.
Output
This will produce the following output on console −
PS C:\Users\Amit\javascript-code> node demo280.js [ -22, 3, 4, 6, 10, 45, 54 ]