Skip to content

Instantly share code, notes, and snippets.

@HallexCosta
Last active March 6, 2021 23:42
Show Gist options
  • Save HallexCosta/9d74e9348948c58fc73180aa1175698c to your computer and use it in GitHub Desktop.
Save HallexCosta/9d74e9348948c58fc73180aa1175698c to your computer and use it in GitHub Desktop.
Merge Sort Algorithm with Javascript (CommonJS)
const { Merge } = require('./Merge)
const a = [15, 5, 24, 8, 1, 3, 16, 10, 20]
Merge.display(a) // output: [15, 5, 24, 8, 1, 3, 16, 10, 20]
Merge.sort(a, 0, a.length - 1)
Merge.display(a) // output: [1, 3, 5, 8, 10, 15, 16, 20, 24]
class Merge {
static sort(a, lb, ub) {
if (lb < ub) {
const mid = parseInt((lb + ub) / 2)
Merge.sort(a, lb, mid)
Merge.sort(a, mid + 1, ub)
Merge.concat(a, lb, mid, ub)
}
}
static concat(a, lb, mid, ub) {
let i = lb
let j = mid + 1
let k = lb
const b = []
while (i <= mid && j <= ub) {
if (a[i] <= a[j]) {
b[k] = a[i++]
} else {
b[k] = a[j++]
}
k++
}
if (i > mid) {
while (j <= ub) {
b[k++] = a[j++]
}
} else {
while (i <= mid) {
b[k++] = a[i++]
}
}
for (k = lb; k <= ub; k++) {
a[k] = b[k]
}
}
static display(a) {
const data = a.join(', ')
console.log(`[${data}]`)
}
}
module.exports = { Merge }
const { deepStrictEqual } = require('assert')
;
(() => {
const expected = [1, 3, 5, 8, 10, 15, 16, 20, 24]
// Should be able apply merge sort with values out of order
{
const a = [15, 5, 24, 8, 1, 3, 16, 10, 20]
Merge.sort(a, 0, a.length - 1)
deepStrictEqual(a, expected)
}
// Should be able apply merge sort with values already sorted
{
const a = [1, 3, 5, 8, 10, 15, 16, 20, 24]
Merge.sort(a, 0, a.length - 1)
deepStrictEqual(a, expected)
}
// Should be able apply merge sort with values inversed
{
const a = [24, 20, 16, 15, 10, 8, 5, 3, 1]
Merge.sort(a, 0, a.length - 1)
deepStrictEqual(a, expected)
}
// Should be able apply merge sort with values repeated
{
const a = [7, 7, 127, 500, 127, 7, 7, 8, 8, 8, 4, 4, 0, 0, 2, 2, 2, 5, 5, 5]
const expected = [0, 0, 2, 2, 2, 4, 4, 5, 5, 5, 7, 7, 7, 7, 8, 8, 8, 127, 127, 500]
Merge.sort(a, 0, a.length - 1)
deepStrictEqual(a, expected)
}
})()
@HallexCosta
Copy link
Author

HallexCosta commented Mar 5, 2021

Add tests to Merge Sort Algorithm

  • Apply merge sort with values out of order.
  • Apply merge sort with values already sorted.
  • Apply merge sort with values inversed.
  • Apply merge sort with values repeated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment