Created
November 20, 2017 22:15
-
-
Save vaidashi/eeecca1a0cdca285dfadd2f13ebb05d1 to your computer and use it in GitHub Desktop.
Sorting Suite with 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
function bubbleSort(list) { | |
var length = list.length; | |
for (var i = 0; i < length; i++) { | |
for (var j = 0; j < (length - i - 1); j++) { | |
if(list[j] > list[j+1]) { | |
var temp = list[j]; | |
list[j] = list[j+1]; | |
list[j+1] = temp; | |
} | |
} | |
} | |
}; | |
var list = [4, 11, 92, 6] | |
bubbleSort(list) | |
console.log(list) | |
function mergeSort(arr) { | |
if (arr.length === 1) { | |
return arr | |
} | |
var middle = Math.floor(arr.length / 2) | |
var left = arr.slice(0, middle) | |
var right = arr.slice(middle) | |
return merge( mergeSort(left), mergeSort(right) ) | |
} | |
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)) | |
} | |
var list = [4, 11, 92, 6, 3, 75, 30, 111] | |
mergeSort(list) | |
// console.log(mergeSort(list)) | |
module.exports = mergeSort |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment