Reputation: 707
so I am trying to enter information into an array in the correct alphabetical order spot as it is entered. Right now I have it entering everything into the array unordered then I order it using a sort method after but my professor says, "To receive full credit, you must insert each item into its sorted position in the array as it is read in. It is not ok to read it all in and call a sort routine." How can I enter the item into the correct spot into the array? This is what I have
public class NumberCollection2
{
String nextName;
int nextNumber;
private Person[] people = new Person[50];
private int size =0;
public void load()
{
try
{
Scanner in = new Scanner(new File ("numbers.txt"));
while (in.hasNextLine())
{
nextName = in.next();
nextNumber = in.nextInt();
people[size]=new Person(nextName, nextNumber);
size++;
in.nextLine();
}
//use exchange sort to sort in ascending alphabetical order
int i, j;
for ( i = 0; i < size - 1; i++ )
{
for ( j = i + 1; j < size; j++ )
{
if ( people[ i ].getName().compareTo(nextName) > 0 )
{
Person temp = people [ i ];
people [ i ] = people [j];
people[j] = temp;
}
}
}
}
Upvotes: 0
Views: 183
Reputation: 2770
Your teacher probably expects from you to implement the InsertSort algoritm. See this sources for more details:
It should look something like:
while (in.hasNextLine())
{
nextName = in.next();
nextNumber = in.nextInt();
for(i = size; i > 0; --i) {
if ( people[i - 1].getName().compareTo(nextName) <= 0 ) {
break;
}
people[i] = people[i-1];
}
people[i] = new Person(nextName, nextNumber);
size++;
in.nextLine();
}
Upvotes: 1