因此,我尝试按照输入时正确的字母顺序将信息输入到数组中。现在,我让它将所有内容无序地输入到数组中,然后我使用排序方法对其进行排序,但我的教授说:“要获得完整的学分,你必须将每个项目插入到数组中读入时的排序位置。它将其全部读入并调用排序例程是不行的。”如何将项目输入到数组的正确位置?这就是我所拥有的
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;
}
}
}
}
最佳答案
您的老师可能希望您实现 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();
}
关于java - 按字符串进入数组按字母顺序排序 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21817877/