【问题标题】:Applying insertion sort to arrays of objects将插入排序应用于对象数组
【发布时间】:2018-11-06 00:00:11
【问题描述】:

我正在尝试将插入排序应用于对象数组,但我的 else if 从未编译并说“错误的操作数类型”。

只是想知道我是否需要创建一个非常具体的compareTo 方法,或者是否有更好的方法在插入排序方法中比较对象数组。

编辑:

所以这是我尝试使用我的compareTo 方法并且它编译但我在else if 上得到一个null pointer exception。为什么?

public static void insertElement(WordClass[] Words, int next)
{
    WordClass value = Words[next];
    int i = next;

    while(true)
    {
        //
        if(i == 0)
        {
            Words[0] = value;
            break;
        }

        else if(Words[i-1].getStr().compareTo(value.getStr()) <= 0)
        {
            Words[i] = value;
            break;
        }
        else
        {
            Words[i] = Words[i-1];
            i--;
        }
    }
}


public static void insertionSort(WordClass[] Words)
{
    for(int i = 1; i< Words.length; i++)
    {
        insertElement(Words, i);
    }
}

     //in WordClass
     public int compareTo(WordClass w) //makes WordClass comparable
{
    return getStr().compareTo(w.getStr()); 

}

【问题讨论】:

  • Words[i-1] == (value)
  • == 返回真或假
  • 那么你怎么能检查说,true小于或等于2

标签: java arrays sorting compareto insertion


【解决方案1】:

对于对象类型,您应该始终使用campareTo 而不是==&lt;= 运算符,除非您想对两个对象变量进行存储以查看它们是否都引用同一个对象。 此外,您的 WordClass 类必须实现 Camparable 接口才能使其正常工作。

【讨论】:

  • 我已经使用 compareTo 进行了编辑,如果有人可以帮助我,我将不胜感激
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 2016-05-05
  • 1970-01-01
  • 1970-01-01
  • 2013-10-05
相关资源
最近更新 更多