
Patrick B. answered 08/09/21
Math and computer tutor/teacher
using namespace std;
#include <iostream>
#include <stdlib.h>
#define ERROR_DELETE_ON_EMPTY_LIST (-1)
#define ERROR_INSERT_ON_FULL_LIST (-2)
#define ERROR_INT_VALUE_ALREADY_EXISTS (-4)
#define ERROR_INVALID_INDEX (-8)
#define MAX_NUM_INT_VALUES (6)
class IntListBase
{
protected:
int A[MAX_NUM_INT_VALUES];
int count;
public:
IntListBase()
{
for (int iLoop=0; iLoop<MAX_NUM_INT_VALUES; iLoop++)
{
A[iLoop]=0;
}
count=0;
}
int GetCount() { return(count); }
int LinearSearchFind(int iTargetIntNumVal)
{
int iIndexPosReturn=-1;
for (int iLoop=0; iLoop<count; iLoop++)
{
if (A[iLoop]==iTargetIntNumVal)
{
iIndexPosReturn = iLoop;
break;
}
}
return(iIndexPosReturn);
}
int IndexerGetAtIndex(int iIndexPos, int * intTargetIntVal)
{
int iReturn=0;
if (iIndexPos>=0 && iIndexPos<count)
{
*intTargetIntVal = A[iIndexPos];
}
else
{
iReturn=ERROR_INVALID_INDEX;
}
return(iReturn);
}
int RemoveDelete(int iIndexPos)
{
int iReturn=0;
if (iIndexPos>=0 && iIndexPos<count)
{
//moves the values one position towards the front and voids the last one
for (int iLoop=iIndexPos; iLoop<count-1; iLoop++)
{
A[iLoop]=A[iLoop++];
}
A[--count]=0;
}
else
{
iReturn = ERROR_INVALID_INDEX;
}
}
};
class UnsortedIntList : public IntListBase
{
public:
int Insert(int iNewIntValue)
{
int iReturn=0;
if (count<MAX_NUM_INT_VALUES)
{
int iSearchFindReturn = LinearSearchFind(iNewIntValue);
if (iSearchFindReturn<0)
{
A[count++]=iNewIntValue;
}
else
{
iReturn = ERROR_INT_VALUE_ALREADY_EXISTS;
}
}
else
{
iReturn = ERROR_INSERT_ON_FULL_LIST ;
}
return(iReturn);
}
};
class SortedIntList: public IntListBase
{
public:
int Insert(int iNewIntValue)
{
int iReturn=0;
if (count<MAX_NUM_INT_VALUES)
{
int iSearchFindReturn = LinearSearchFind(iNewIntValue);
if (iSearchFindReturn<0)
{
//insertion sort
int iIndexPos=count-1;
while (A[iIndexPos]>iNewIntValue)
{
A[iIndexPos+1]=A[iIndexPos];
iIndexPos--;
if (iIndexPos<0)
{
break;
}
}
iIndexPos++;
A[iIndexPos]=iNewIntValue;
count++;
}
else
{
iReturn = ERROR_INT_VALUE_ALREADY_EXISTS;
}
}
else
{
iReturn = ERROR_INSERT_ON_FULL_LIST ;
}
return(iReturn);
}
};
int main()
{
SortedIntList sortedIntList;
UnsortedIntList unsortedIntList;
int iNums[] = {1 , 1 , 0 , 5 , 0 , 2 , 1 , 5 , 4 , 1 , 5 , 4 , 3};
int nCount=13;
for (int iLoop=0; iLoop<nCount; iLoop++)
{
sortedIntList.Insert(iNums[iLoop]);
unsortedIntList.Insert(iNums[iLoop]);
}
nCount = sortedIntList.GetCount();
int iNumVal;
cout << "Sorted List:" << endl;
for (int iLoop=0; iLoop<nCount; iLoop++)
{
sortedIntList.IndexerGetAtIndex(iLoop,&iNumVal);
cout << iNumVal << endl;
}
nCount = unsortedIntList.GetCount();
cout << "unsorted List:" << endl;
for (int iLoop=0; iLoop<nCount; iLoop++)
{
unsortedIntList.IndexerGetAtIndex(iLoop,&iNumVal);
cout << iNumVal << endl;
}
}