Last active
August 29, 2015 14:14
-
-
Save NathanEpstein/835dfa5389d38d9438b2 to your computer and use it in GitHub Desktop.
bubble sort and merge sort in JS
This file contains hidden or 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
bubbleSort = function(array){ | |
var swaps = 0; | |
var comparisions = 0; | |
var bool = true; | |
if (array.length <= 1){ | |
bool = false; | |
return array; | |
} | |
while (bool){ | |
var count = 0; | |
for (var i=0; i<array.length-1; i++){ | |
comparisions++; | |
if (array[i] > array[i+1]){ | |
swaps++; | |
var a = array[i]; | |
var b = array[i+1]; | |
array[i] = b; | |
array[i+1] = a; | |
} | |
else { | |
count++; | |
} | |
} | |
if (count == array.length-1){ | |
bool = false; | |
console.log('swap: '+swaps); | |
console.log('comparisons: '+comparisions); | |
return array; | |
} | |
} | |
} | |
var mergeSort = function(array) { | |
if (array.length <= 1) return array; | |
var length = Math.floor(array.length / 2); | |
var leftArr = array.slice(0, length); | |
var rightArr = array.slice(length, array.length); | |
var left = mergeSort(leftArr); | |
var right = mergeSort(rightArr); | |
return merge(left, right); | |
}; | |
var merge = function(left, right) { | |
var sorted = []; | |
var iteration = left.length + right.length; | |
for (var i = 0; i < iteration; i++) { | |
if(right[0] !== undefined && left[0]!== undefined){ | |
if (left[0] < right[0]) { sorted.push(left.shift()); } | |
else { sorted.push(right.shift()); } | |
} | |
else if( left[0] !== undefined){ | |
sorted.push(left.shift()); | |
} | |
else{ | |
sorted.push(right.shift()); | |
} | |
} | |
return sorted; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment