因此我尝试在输入时在正确的字母顺序点中将信息输入到数组中。现在我把它输入到无序的数组中,然后我使用排序方法对它进行排序,但是我的教授说,“要获得完全的功劳,你必须将每个项目插入数组中的排序位置,因为它被读入。它是不是可以全部阅读并调用排序程序。“如何将项目输入到阵列中的正确位置?这就是我所拥有的
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;
}
}
}
}
答案 0 :(得分:1)
您的老师可能希望您实现InsertSort算法。有关详细信息,请参阅此来源:
它应该类似于:
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();
}