Implement Bubble sort with negative and positive numbers – JavaScript?



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
]
Updated on: 2020-11-09T08:13:49+05:30

898 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements