Skip to content

Instantly share code, notes, and snippets.

@quimbs
Last active August 29, 2015 14:17
Show Gist options
  • Save quimbs/61914ff8bbc0fd72eaf4 to your computer and use it in GitHub Desktop.
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
// '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