arrayManipulation.h

/*
 * arraySearching.h
 *
 *  Created on: May 9, 2020
 *      Author: zeil
 */

#ifndef ARRAYMANIPULATION_H_
#define ARRAYMANIPULATION_H_

/**
 * Search an array for a key value.
 *
 * @param array  an array of values, in any particular order
 * @param numElements  the number of elements in the array
 * @key the value to search for
 * @return the position where the key was found, or -1 if the key is not
 *         in the array.
 */
template <typename Element>
int sequentialSearch(const Element* array, int numElements, const Element& key)
{
    for (int i = 0; i < numElements; ++i)
    {
       if (array[i] == key)
       {
         return i;
       }
    }
    return -1;
}

/**
 * Add a value to the end of an array if it is not already in there.
 *
 * @param array  an array of values, in any particular order
 * @param numElements  the number of elements in the array, will be incremented by one
 *                     if the element is added
 * @newElement the value to add
 * @return true iff the element was added, false if the value was already in the array.
 */
template <typename Element>
int addIfNotPresent(Element* array, int& numElements, const Element& newElement)
{
    if (sequentialSearch(array, numElements, newElement) < 0)
    {
       array[numElements] = newElement;
       ++numElements;
       return true;
    }
    else
       return false;
}


/**
 * Remove a value from an array if it is in there.
 *
 * @param array  an array of values, in any particular order
 * @param numElements  the number of elements in the array, will be decremented by one
 *                     if the element is found and removed.
 * @key the value to remove
 * @return true iff the element was found and removed, false if the value was not in the array.
 */
template <typename Element>
int removeIfPresent(Element* array, int& numElements, const Element& key)
{
    int pos = sequentialSearch(array, numElements, key);
    if (pos >= 0)
    {
       for (int i = pos+1; i < numElements; ++i)
         array[i-1] = array[i];
       --numElements;
       return true;
    }
    else
       return false;
}





#endif /* ARRAYMANIPULATION_H_ */

unformatted source