A simple implementation of a binary search algorithm for string arrays using Amiga OS semantics. wasBinarySearch
takes as parameters:
Note that the algorithm assumes that the array to be searched has been previously sorted.
/*************************************************************************/ /* Copyright (C) 2015 Wizardry and Steamworks - License: GNU GPLv3 */ /*************************************************************************/ /* */ /* wasBinarySearch */ /* */ /* An implementation of a binary search algorithm for strings. */ /* */ /* Compile on Amiga OS using SAS/C: sc link wasBinarySearch.c */ /* */ /*************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <proto/exec.h> #include <proto/dos.h> /*************************************************************************/ /* Copyright (C) 2015 Wizardry and Steamworks - License: GNU GPLv3 */ /*************************************************************************/ LONG wasBinarySearch(UBYTE *e, UBYTE **a, ULONG l, ULONG r) { LONG m = (r + l) / 2; LONG x = strcmp(e, a[m]); if(x == 0) return m; if(l == r) return -1; if(x < 0) r = m - 1; if(x > 0) l = m + 1; return binarySearch(e, a, l, r); } int main(void) { UBYTE *a[10] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" }; Printf("%ld\n", binarySearch("c", a, 0, 9)); }