[英]Creating a 'sort' method for array objects in a linked list
I have a project that requires we create a an object array and then we place that in a linked list, I am kind of stuck because I have trouble writing/implementing my sort method that is supposed to sort the the linked list. 我有一个项目,要求我们创建一个对象数组,然后将其放置在链接列表中,这有点卡住,因为我在编写/实现应该对链接列表进行排序的排序方法时遇到麻烦。 Here is my code of how far I've gone.
这是我走了多远的代码。 By the way, the object name is 'temperature';
顺便说一下,对象名称是“温度”; Thank you.
谢谢。
public class SelectionSort
{
private static void SelectionSort (Temperature[] array, int size)
{
for ( int i = 0; i < size - 1; i++ )
{
int indexLowest = i;
for ( int j = i + 1; j < size; j++ )
{
if ( array[j] < array[indexLowest] )
indexLowest = j;
if ( array[indexLowest] != array[i] )
{
Temperature temp = array[indexLowest];
array[indexLowest] = array[i];
array[i] = temp;
}// if
}//for j
}// for i
}// method
}
I think, your problem is the line 我想,你的问题是线
if ( array[j] < array[indexLowest] )
Both - array[j]
and array[indexLowest]
- are of type Temperature, according to your method's signature. 根据您方法的签名,
array[j]
和array[indexLowest]
都属于温度类型。 So they are not primitive types and thus cannot be compared with <
. 因此它们不是原始类型,因此无法与
<
进行比较。 This obviously results in a compiler error, that you really should have told us. 显然,这会导致编译器错误,您确实应该告诉我们。
To compare objects like this, you have two possibilities: 要比较这样的对象,您有两种可能性:
1) Let the class Temperature
implement Comparable<Temperature>
. 1)让
Temperature
类实现Comparable<Temperature>
。 This interface will force you to add a method public int compareTo(Temperatue other)
to your class Temperature
. 该接口将迫使您向类
Temperature
添加public int compareTo(Temperatue other)
方法。 Implement this in the following way: 通过以下方式实现:
@Override
public int compareTo(Temperatue other) {
if (/* this is smaller than other */) {
return -1;
} else if (/* this is greater than other */) {
return 1;
} else {
return 0;
}
}
You could return any other positive or negative integer if you want to. 如果需要,可以返回任何其他正整数或负整数。 Implement the comparisonyourself based on the fields in
Temperature
. 根据
Temperature
场进行比较。
Use this in your problematic line as: 在有问题的行中将其用作:
if ( array[j].compareTo(array[indexLowest]) < 0 )
2) Write a Comparator for your class Temperature. 2)为您的班级温度写一个比较器。
public class TemperatureComparator implements Comparator<Temperature> {
public int compare(Temperature t1, Temperature t2) {
if (/* t1 is smaller than t2 */) {
return -1;
} else if (/* t1 is greater than t2 */) {
return 1;
} else {
return 0;
}
}
}
The logic is similar. 逻辑类似。 Now you can use this comparator in your sort method
现在您可以在排序方法中使用此比较器
private static void SelectionSort (Temperature[] array, int size) {
Comparator<Temperature> comparator = new TemperatureComparator();
...
if ( comparator.compare(array[j], array[indexLowest]) < 0 )
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.