Path: blob/master/libmupen64plus/mupen64plus-video-rice/src/CSortedList.h
2 views
/*1Copyright (C) 2003 Rice196423This program is free software; you can redistribute it and/or4modify it under the terms of the GNU General Public License5as published by the Free Software Foundation; either version 26of the License, or (at your option) any later version.78This program is distributed in the hope that it will be useful,9but WITHOUT ANY WARRANTY; without even the implied warranty of10MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the11GNU General Public License for more details.1213You should have received a copy of the GNU General Public License14along with this program; if not, write to the Free Software15Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.16*/1718#ifndef _SORTED_LIST_H_19#define _SORTED_LIST_H_2021#include <cstring>2223template<class Key, class Element>24class CSortedList25{26private:27Key *keys;28Element *elements;29int curSize;30int maxSize;3132public:33CSortedList(int size=1000)34{35maxSize = size;36curSize = 0;37keys = new Key[size];38elements = new Element[size];39}4041~CSortedList()42{43delete [] keys;44delete [] elements;45}4647int size()48{49return curSize;50}5152void clear()53{54curSize = 0;55}5657void add(Key key, Element ele)58{59int i = find(key);60if( i >= 0 )61{62elements[i] = ele;63return;64}6566if( curSize == maxSize )67{68// Need to increase maxSize69Key *oldkeys = keys;70Element *oldelements = elements;71int oldmaxsize = maxSize;72maxSize *= 2;7374keys = new Key[maxSize];75elements = new Element[maxSize];76std::memcpy(keys,oldkeys,oldmaxsize*sizeof(Key));77std::memcpy(elements,oldelements,oldmaxsize*sizeof(Element));78}7980for( i=0; i<curSize; i++ )81{82if( keys[i] > key )83{84// Found the spot85break;86}87}8889for( int j=curSize; j>i; j-- )90{91keys[j] = keys[j-1];92elements[j] = elements[j-1];93}9495keys[i] = key;96elements[i] = ele;97curSize++;98}99100Element operator[](int index)101{102if( index >= curSize )103index = curSize-1;104else if( index < 0 )105index = 0;106107return elements[index];108}109110Element get(Key key)111{112int index = Find(key);113return this->operator[](index);114}115116// Binary search117int find(Key key)118{119if( curSize <= 0 )120return -1;121122int dwMin = 0;123int dwMax = curSize - 1;124int index = -1;125126int dwRange;127int dwIndex;128129while (true)130{131dwRange = dwMax - dwMin;132dwIndex = dwMin + (dwRange/2);133134if( keys[dwIndex] == key )135{136index = dwIndex;137break;138}139140// If the range is 0, and we didn't match above, then it must be unmatched141if (dwRange == 0)142break;143144// If lower, check from min..index145// If higher, check from index..max146if (key < keys[dwIndex])147{148// Lower149dwMax = dwIndex;150}151else152{153// Higher154dwMin = dwIndex + 1;155}156}157158return index;159}160};161162#endif163164165166