Skip to content

Instantly share code, notes, and snippets.

@thomhos
Last active February 3, 2018 21:26
Show Gist options
  • Save thomhos/feb87cad7f913db13ca33a674f86ea79 to your computer and use it in GitHub Desktop.
Save thomhos/feb87cad7f913db13ca33a674f86ea79 to your computer and use it in GitHub Desktop.
bubble sort and binary search
const testArray = [1,2,4,5,3,9,7,8,5,4,9,39,203,495,404,93,39]
const target = 93
const bubbleSort = (inArr) => {
const arr = [...inArr]
for(let i = 0; i < arr.length ; i++) {
for(let j = 0; j < arr.length ; j++) {
if(arr[j] > arr[j + 1]) {
const t = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = t
}
}
}
return arr
}
const binarySearch = (arr, val) => {
let lowIndex = 0
let highIndex = arr.length - 1
let middleIndex
while(lowIndex <= highIndex) {
middleIndex = Math.floor((lowIndex + highIndex) / 2)
if(arr[middleIndex] < val) {
// Target must be on right side
lowIndex = middleIndex + 1
} else if(arr[middleIndex] > val) {
// Target must be on left side
highIndex = middleIndex - 1
} else {
console.log('Found in position ', middleIndex)
return middleIndex
}
}
console.log('not found..')
return false
}
console.log(bubbleSort(testArray))
console.log(testArray)
// console.log(binarySearch(bubbleSort(testArray), target))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment