Skip to content

Instantly share code, notes, and snippets.

@tomaslibal
Last active January 19, 2017 15:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomaslibal/5124095 to your computer and use it in GitHub Desktop.
Save tomaslibal/5124095 to your computer and use it in GitHub Desktop.
A binary search like function in processing. There are no pointers by default in processing so this function works with array indexes. This example works with an array of ordered strings.
#include <cstring>
#include <cmath>
bool bsearch(const char* array, char ch)
{
int a = 0; // start of the search array
int b = strlen(array); // end of the search array
int m = 0; // the middle value
int prev; // remembers the previous middle value
while(true) {
prev = m; // prev gets the old middle value
m = floor((a+b)/2); // m gets a new middle value
if(prev == m) { break; } // reached the end, break out of the loop
if(array[m] == ch) { return true; } // found the lookup, return the index position
// On the next line, for processing.js the comparison method will be "if(stack[m] > lookup)". The following is for processing in java:
else if(array[m] > ch) { // the lookup cannot be in the right hand side part of the array
b = m - 1; // so bound the end of the array at m: <a, m>
}else { // otherwise the lookup cannot be in the left hand side part of the array
a = m + 1; // so bound the search array from the left at m: <m, b>
}
}
return false; // not found
}
String[] stack = {"Al", "B", "Bi", "Fe", "Mn", "Mg", "O", "Y", "Zn"};
String lookup = "Y";
// A binary-search like function for looking up a string in an array of ordered strings
// @param String lookup is what we want to find in the array
// @param String[] stack is the array that is being searched
// @return int the index position of the lookup in the array or -1 if not found
int bsearch(String lookup, String[] stack)
{
int a = 0; // start of the search array
int b = stack.length; // end of the search array
int m = 0; // the middle value
int prev; // remembers the previous middle value
while(true) {
prev = m; // prev gets the old middle value
m = floor((a+b)/2); // m gets a new middle value
if(prev == m) { break; } // reached the end, break out of the loop
if(stack[m] == lookup) { return m; } // found the lookup, return the index position
// On the next line, for processing.js the comparison method will be "if(stack[m] > lookup)". The following is for processing in java:
else if(stack[m].compareTo(lookup) > 0) { // the lookup cannot be in the right hand side part of the array
b = m - 1; // so bound the end of the array at m: <a, m>
}else { // otherwise the lookup cannot be in the left hand side part of the array
a = m + 1; // so bound the search array from the left at m: <m, b>
}
}
return -1; // not found
}
println(bsearch(lookup, stack));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment