I have an array where of integers that has to be sorted and inserted into the correct place in the array for each number, not just at the end. All of this is done in the add method. This is what i have so far.
package sortedintlist;
public class SortedIntList extends IntList{
protected int num = 0;
protected int place = 0;
public SortedIntList(int size)
{
super(size);
}
public void add(int value)
{
if (numElements == list.length)
System.out.println("Can't add, list is full");
else
{
int i = 1;
while (i >= 0 && num < value)
{
i++;
}
while (numElements > i)
{
list[i] = list[i-1];
i--;
}
}
}
}
This is the list of numbers:
public class ListTest
{
public static void main(String[] args)
{
SortedIntList myList = new SortedIntList(10);
myList.add(100);
myList.add(50);
myList.add(200);
myList.add(25);
System.out.println(myList);
}
}
This was the original IntList that contains the original Add method:
public class IntList
{
protected int[] list;
protected int numElements = 0;
//-------------------------------------------------------------
// Constructor -- creates an integer list of a given size.
//-------------------------------------------------------------
public IntList(int size)
{
list = new int[size];
}
//-------------------------------------------------------------
// Adds an integer to the list. If the list is full,
// prints a message and does nothing.
//-------------------------------------------------------------
public void add(int value)
{
if (numElements == list.length)
System.out.println("Can't add, list is full");
else
{
list[numElements] = value;
numElements++;
}
}
//-------------------------------------------------------------
// Returns a string containing the elements of the list with their
// indices.
//-------------------------------------------------------------
public String toString()
{
String returnString = "";
for (int i=0; i<numElements; i++)
returnString += i + ": " + list[i] + "\n";
return returnString;
}
}