Tuesday, 24 December 2013

The Ordered Array Class that Differs from the Unordered Array

template <class T>
class OrderedArray
{
public:
int push(T val)
{
assert(m_array != NULL);
if(m_numElements >= m_maxSize)
{
Expand();
}
for(int i = 0; i < m_numElements; i++)
{
if(m_array[i] > val)
break;
}
for(int k = m_numElements; k > i; k—)
{
m_array[k] = m_array[k - 1];
}
m_array[i] = val;
m_numElements++;
return i;
}
};
Another option for inserting an item into an ordered array is to use a modified binary search to find the index closest to where the item would need to be inserted
and start the stepping from that point.
Share it Please

0 comments:

Post a Comment

Copyright @ 2013 Learn About Computers and Programming. Designed by Templateism | Love for The Globe Press