Patrick B. answered 05/08/21
Math and computer tutor/teacher
class SortedList
{
protected String A[];
protected int numRecs;
public SortedList()
{
A = new String[1];
numRecs=0;
}
public void InsertAddNew(String newStr)
{
if (numRecs==0)
{
A[0] = new String(newStr);
numRecs=1;
}
else
{
String tempArray[] = new String[numRecs+1];
//copies to tempArray
for (int iLoop=0; iLoop<numRecs; iLoop++)
{
tempArray[iLoop]=A[iLoop];
}
//1-pass Insertion Sort is all that is needed
int j = numRecs-1;
while (
(j >= 0) && (newStr.compareTo(tempArray[j])<0 )
)
{
tempArray[j + 1] = tempArray[j];
j = j - 1;
} //while
tempArray[j + 1] = new String(newStr);
A = tempArray;
tempArray=null;
numRecs++;
} //if
} //Insert Add new
public String IndexerGetAtIndex(int iIndexPos)
{
String strReturn=null;
if (iIndexPos>=0 && iIndexPos<numRecs)
{
strReturn = A[iIndexPos];
}
return(strReturn);
}
public int GetNumRecs() { return(numRecs); }
public static void main(String args[])
{
SortedList mySortedList =new SortedList();
String str="?";
str = "grapes";
mySortedList.InsertAddNew(str);
str = "watermelon";
mySortedList.InsertAddNew(str);
str = "pineapple";
mySortedList.InsertAddNew(str);
str = "strawberries";
mySortedList.InsertAddNew(str);
int N = mySortedList.GetNumRecs();
for (int iLoop=0; iLoop<N; iLoop++)
{
System.out.println(mySortedList.IndexerGetAtIndex(iLoop));
}
}
}