Last active
August 29, 2015 14:17
-
-
Save quimbs/61914ff8bbc0fd72eaf4 to your computer and use it in GitHub Desktop.
Binary search function to find the note in an array sorted by frequency that is closest to the one passed as a parameter
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
// 'notes' is an array of objects like { note: 'A4', frequency: 440 }. | |
// See initialization in the source code of the demo | |
var findClosestNote = function(freq, notes) { | |
// Use binary search to find the closest note | |
var low = -1, high = notes.length; | |
while (high - low > 1) { | |
var pivot = Math.round((low + high) / 2); | |
if (notes[pivot].frequency <= freq) { | |
low = pivot; | |
} else { | |
high = pivot; | |
} | |
} | |
if(Math.abs(notes[high].frequency - freq) <= Math.abs(notes[low].frequency - freq)) { | |
// notes[high] is closer to the frequency we found | |
return notes[high]; | |
} | |
return notes[low]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment