Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions sorting/bubblesort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// array to sort
var array = [9, 2, 5, 6, 4, 3, 7, 10, 1, 8, 11, 12, 13, 14, 15];

// swap function helper
function swap(array, i, j) {
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}

// Bubble Sort
function bubbleSort(array) {
var swapped;
do {
swapped = false;
for(var i = 0; i < array.length; i++) {
if(array[i] && array[i + 1] && array[i] > array[i + 1]) {
swap(array, i, i + 1);
swapped = true;
}
}
} while(swapped);
return array;
}

console.log(bubbleSort(array.slice()));
38 changes: 38 additions & 0 deletions sorting/mergesort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// split array into halves
function mergeSort (arr) {
if (arr.length === 1) {
// return once we hit an array with a single item
return arr
}

const middle = Math.floor(arr.length / 2) // get the middle item of the array rounded down
const left = arr.slice(0, middle) // items on the left side
const right = arr.slice(middle) // items on the right side

return merge(
mergeSort(left),
mergeSort(right)
)
}

// compare the arrays item by item and return the concatenated result
function merge (left, right) {
let result = []
let indexLeft = 0
let indexRight = 0

while (indexLeft < left.length && indexRight < right.length) {
if (left[indexLeft] < right[indexRight]) {
result.push(left[indexLeft])
indexLeft++
} else {
result.push(right[indexRight])
indexRight++
}
}

return result.concat(left.slice(indexLeft)).concat(right.slice(indexRight))
}

const list = [2, 5, 1, 3, 7, 2, 3, 8, 6, 3]
console.log(mergeSort(list))