Was it helpful?

Question

Comparing adjacent element and swap - JavaScript?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

This is the concept of Bubble Sort. It compares to adjacent element if it is lesser it will swap the value.

Example

Following is the code −

var numbers = [10, 100, 30, 40, 90, 4, 91, 56, 78];
function bubbleSorting(numbers) {
   for (var outer = 0; outer < numbers.length; outer++) {
      for (var inner = 0; inner < numbers.length; inner++) {
         if (numbers[outer] < numbers[inner]) {
            var temp = numbers[outer];
            numbers[outer] = numbers[inner];
            numbers[inner] = temp;
         }
      }
   }
   return numbers;
}
console.log(bubbleSorting(numbers));

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo233.js.

Output

The output is as follows −

PS C:\Users\Amit\JavaScript-code> node demo233.js
[
    4, 10, 30,  40, 56,
   78, 90, 91, 100
]
raja
Published on 03-Oct-2020 18:35:38
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top