Last active
February 3, 2018 21:26
-
-
Save thomhos/feb87cad7f913db13ca33a674f86ea79 to your computer and use it in GitHub Desktop.
bubble sort and binary search
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
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