java - 按字符串进入数组按字母顺序排序 java

标签 java arrays sorting

因此,我尝试按照输入时正确的字母顺序将信息输入到数组中。现在,我让它将所有内容无序地输入到数组中,然后我使用排序方法对其进行排序,但我的教授说:“要获得完整的学分,你必须将每个项目插入到数组中读入时的排序位置。它将其全部读入并调用排序例程是不行的。”如何将项目输入到数组的正确位置?这就是我所拥有的

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/

相关文章:

c++ - 使用大数组索引增加访问时间

arrays - 从 R 中的另一个 3D 数组填充 3D 数组的最快方法

c - 最有效的动态排序方法

java - 更改 JTable 中的列标题

java - Spring MVC 页面

java - 如何双重转义双引号?

javascript - 如何通过关键词获取最相关的问题

javascript - 在 React 中将键排序到映射中

ios 使用字典对数组进行排序

JavaFX8 后台线程仍然干扰 GUI