About

A simple implementation of a binary search algorithm for string arrays using Amiga OS semantics. wasBinarySearch takes as parameters:

  1. the string to search for,
  2. the array to search in,
  3. the lower-bound index to start the search from,
  4. the upper-bound index to stop at

Note that the algorithm assumes that the array to be searched has been previously sorted.

Code

wasBinarySearch.c
/*************************************************************************/
/*    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));
}

amiga/development/algorithms/binary_search.txt ยท Last modified: 2022/04/19 08:28 by 127.0.0.1

Access website using Tor Access website using i2p Wizardry and Steamworks PGP Key


For the contact, copyright, license, warranty and privacy terms for the usage of this website please see the contact, license, privacy, copyright.