Created
March 18, 2017 02:18
-
-
Save AndrewHuffman/ee619db7b4e7e05c47b8244292902951 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function mergeSort(arr) { | |
arr = arr || []; | |
if (arr.length <= 1) { | |
return arr; | |
} | |
var midpoint = Math.floor(arr.length / 2) | |
, arr1 = arr.slice(0, midpoint) | |
, arr2 = arr.slice(midpoint, arr.length) | |
; | |
return merge(mergeSort(arr1), mergeSort(arr2)) | |
} | |
function merge(arr1, arr2) { | |
var sorted = []; | |
do { | |
var head1 = arr1.shift() | |
, head2 = arr2.shift(); | |
if (!head1) { | |
if (head2) { | |
sorted.push(head2) | |
} | |
break | |
} | |
if (!head2) { | |
if (head1) { | |
sorted.push(head1) | |
} | |
break | |
} | |
if (head1 < head2) { | |
sorted.push(head1); | |
arr2.unshift(head2); | |
} else { | |
sorted.push(head2); | |
arr1.unshift(head1); | |
} | |
} while (true); | |
if (arr1.length > 0) { | |
arr1.forEach(function (char) { | |
sorted.push(char); | |
}); | |
} | |
if (arr2.length > 0) { | |
arr2.forEach(function(char) { | |
sorted.push(char) | |
}); | |
} | |
return sorted; | |
} | |
var _ = require('lodash') | |
const N = 26 | |
, A = 'a'; | |
function randArray(arrSize) { | |
function randInt(max) { | |
return Math.round(Math.random() * max); | |
} | |
arrSize = arrSize || N; | |
return _(_.range(arrSize)).map(() => { | |
return String.fromCharCode(A.charCodeAt(0) + randInt(N)); | |
}).value(); | |
} | |
const alphabet = ((a, n) => { | |
const code = a.charCodeAt('0'); | |
return _.range(n).map((_, idx) => String.fromCharCode(code + idx) ).join(''); | |
})(A, N); | |
const alphaArray = alphabet.split(''); | |
var arr = randArray(26); | |
console.log('rand->', arr.join(', ')); | |
console.log('sort->', mergeSort(arr).join(', ')); | |
var arr = _.reverse(alphaArray) | |
console.log('rand->', arr.join(', ')) | |
console.log('sort->', mergeSort(arr).join(', ')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment