
Patrick B. answered 05/07/21
Math and computer tutor/teacher
Use an ArrayList....
//********************************************************************************//
import java.util.ArrayList;
class SortedList
{
protected ArrayList<String> A;
protected int numRecs;
public SortedList()
{
A = new ArrayList<String>();
numRecs=0;
}
public int GetNumRecs() { return(numRecs); }
public void InsertAddNew(String newStr)
{
int iIndexPos=-1;
if (numRecs==0)
{
A.add(newStr);
numRecs=1;
}
else
{
String curStr;
//lienar searches for string that is GREATER
for (int iLoop=0; iLoop<numRecs; iLoop++)
{
curStr = A.get(iLoop);
if (newStr.compareTo(curStr)<0)
{
iIndexPos=iLoop;
break;
}
} //for
if (iIndexPos==-1) //new String is the GREATEST , so it belongs at the end
{
A.add(newStr);
}
else
{
A.add(iIndexPos,newStr);
}
numRecs++;
} //else
}
public String IndexerGetAtIndex(int iIndexPos)
{
String strReturn = null;
if (iIndexPos>=0 && iIndexPos<numRecs)
{
strReturn = (String)A.get(iIndexPos);
return(strReturn);
}
return(strReturn);
}
public static void main(String args[])
{
SortedList mySortedList = new SortedList();
mySortedList.InsertAddNew("grapes");
mySortedList.InsertAddNew("pineapple");
mySortedList.InsertAddNew("caneteloupe");
mySortedList.InsertAddNew("watermelon");
mySortedList.InsertAddNew("cherries");
mySortedList.InsertAddNew("strawberry");
mySortedList.InsertAddNew("apple");
mySortedList.InsertAddNew("banana");
int N = mySortedList.GetNumRecs();
for (int iLoop=0; iLoop<N; iLoop++)
{
System.out.println(mySortedList.IndexerGetAtIndex(iLoop));
}
}
}
Jule J.
could you show it without using ArrayList i am not really familiar with that.05/07/21