- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ]
Advertisements