Skip to content

Commit

Permalink
Adding bubble sort algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
Felipe Natan committed Mar 5, 2020
1 parent 5773877 commit c0eecc5
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 3 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
# Data Structures and Algorithms
>Implementation of some Data Structures and Algorithms in JavaScript
## Algorithms
- BubbleSort

## Data Structures
- Deque
- Priority Queue
Expand All @@ -13,9 +16,6 @@
- Stack
- Stack(Array-based)

## Algorithms
- Not implemented yed :(

## Installation

This is Node.js module available through npm.
Expand Down
18 changes: 18 additions & 0 deletions src/algorithms/sorting/bubbleSort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const reverse = require('./reverseArray');

function bubbleSort(arr){
let arr2 = [...arr];
for(let i = 0; i < arr2.length; i++){
for(let j = i+1; j < arr2.length; j++){
if(arr2[i] > arr2[j]){
let temp = arr2[i];
arr2[i] = arr2[j];
arr2[j] = temp;
}
}
}

return arr2;
}

module.exports = {sort:bubbleSort , reverse};
8 changes: 8 additions & 0 deletions src/algorithms/sorting/reverseArray.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
function reverse(arr){
let reversedArr = []
for(let i = arr.length-1; i >= 0; i--)
reversedArr.push(arr[i]);
return reversedArr;
}

module.exports = reverse;
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
/* eslint-disable global-require */
module.exports = {
/* Algorithms */
BubbleSort: require('./algorithms/sorting/bubbleSort'),
/* Data Structures */
Set: require('./data-structures/set/set'),
Stack: require('./data-structures/stack/stackObject'),
Expand Down
18 changes: 18 additions & 0 deletions test/sorting/bubbleSort.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const assert = require('assert');
const BubbleSort = require('../../src/algorithms/sorting/bubbleSort');

describe('BubbleSort', function() {
const arr = [6,2,7,15,3,4,10,-8,56];
const sortedArr = [-8,2,3,4,6,7,10,15,56];
const reversedArr = [56,15,10,7,6,4,3,2,-8];

it('should sort an array', () => {
assert.deepEqual(BubbleSort.sort(arr), sortedArr);
});


it('should return a reversed array', () => {
let tempArr = BubbleSort.sort(arr);
assert.deepEqual(BubbleSort.reverse(tempArr), reversedArr);
});
});

0 comments on commit c0eecc5

Please sign in to comment.