luis-agm
7/23/2017 - 12:56 AM

## Sorting algorithms in JavaScript

Sorting algorithms in JavaScript

``````// Bubble-sort (pure-function): if it's higher than the next one, swap. O(N^2)

const wat = [2,5,4,3,6,7,2,4,0,8,1,9]

function bubbleSort(array){
const wat = [].concat(array)
for(let i = wat.length - 1; i > 1; i--){
for(let j = 0; j < i; j++){
if(wat[j]>wat[j+1]){
[wat[j], wat[j+1]] = [wat[j+1], wat[j]]
}
}
}
return wat;
}

// Binary search: Compares with middle and decides which half to look at. O(log N)

const ordered = bubbleSort(arr);

function binarySearch(value, array){
let highIndex = ordered.length;
let lowIndex = 0;

while(lowIndex <= highIndex){
const middleIndex = Math.floor((lowIndex + highIndex) / 2);

// Value is lower than middle, look at lower half
if(array[middleIndex] > value) { highIndex = middleIndex - 1; }
// Value is higher than middle, look at higher half
else if(array[middleIndex] < value) {lowIndex = middleIndex + 1;}

// Match!!
else {
lowIndex = highIndex + 1; // Stop the while cycle
return middleIndex;
}
}
}``````