Reputation: 57
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
}
Upvotes: 0
Views: 89
Reputation: 20618
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. 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>
. This interface will force you to add a method public int compareTo(Temperatue other)
to your class Temperature
. 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
.
Use this in your problematic line as:
if ( array[j].compareTo(array[indexLowest]) < 0 )
2) Write a Comparator for your class Temperature.
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 )
...
}
Upvotes: 1