Plan 9 from Bell Labs’s /usr/web/sources/contrib/steve/root/sys/src/cmd/seft/tst.c

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


/*******************************************************************************
*
* Project:      seft (search engine for text)
*
* File:         tst.c
*
* Author:       Owen de Kretser ([email protected])
*
* Organisation: Dept. of CS&SE, University of Melbourne
*
* Date:         April 1999
*
* Purpose:      ternary search tree functions
*
* Notes:        adapted from Bentley & Sedgewick
* 
*******************************************************************************/


/***** #includes **************************************************************/

#include "tst.h"
#include "util.h"


Tptr 
tst_insert(Tptr p, char *s, int index)
{   
    if (p == NULL) 
        {
        p = (Tptr) safe_malloc(sizeof(Tnode));
        p->splitchar = *s;
        p->lokid = p->eqkid = p->hikid = NULL;
        p->term_index = NOT_FOUND;
        }
    if (*s < p->splitchar)
        {
        p->lokid = tst_insert(p->lokid, s, index);
        }
    else if (*s == p->splitchar) 
        {
        if (*s == '\0')
            {
            p->term_index = index;
            }
        else
            {
            p->eqkid = tst_insert(p->eqkid, ++s, index);
            }
        } 
    else
        {
        p->hikid = tst_insert(p->hikid, s, index);
        }

    return (p);
}

void 
cleanup(Tptr p)
{   
    if (p) 
        {
		cleanup(p->lokid);
		if (p->splitchar) 
            {
            cleanup(p->eqkid);
            }
		cleanup(p->hikid);
		free(p);
        }
}

int 
tst_search(Tptr root,char *s)
{   
    Tptr p;
    p = root;
    while (p) 
        {
        if (*s < p->splitchar)
            {
            p = p->lokid;
            }
        else if (*s == p->splitchar)  
            {
            if (*s++ == 0)
                {
                return (p->term_index);
                }
            p = p->eqkid;
            } 
        else
            {
            p = p->hikid;
            }
        }

    return (NOT_FOUND);
}



Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to [email protected].