Skip to content

Instantly share code, notes, and snippets.

@jas0ncn
Created February 13, 2017 12:55
Show Gist options
  • Save jas0ncn/e9007f7a966a451fb7f5ea7fb48bb194 to your computer and use it in GitHub Desktop.
Save jas0ncn/e9007f7a966a451fb7f5ea7fb48bb194 to your computer and use it in GitHub Desktop.
JavaScript sorting algorithm
const arr = [16, 31, 12, 1, 9, 23, 10]
// bubble sort
function bubble (arr) {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j+1])
[ arr[j], arr[j+1] ] = [ arr[j+1], arr[j] ]
}
}
return arr
}
console.log(`Bubble sort: ${bubble(arr)}`)
// quick sort
function quick (arr) {
if (arr.length <= 1) return arr
const middleIndex = Math.floor(arr.length / 2)
const middle = arr.splice(middleIndex, 1)
const left = []
const right = []
arr.forEach(v => {
if (v < middle[0]) left.push(v)
else right.push(v)
})
return quick(left).concat(middle, quick(right))
}
console.log(`Quick sort: ${quick(arr)}`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment