I am working on a program that will take a list of temperatures(double) and days(string) and implement the list using an array of objects. Then I need to sort the objects using an insertion sort algorithm. The output of the program should be the original order and the sorter output. However I am a little confused on how I can go about sorting the temperatures. I implemented the Comparable interface and wrote the insertion sort. I just have to have the original arraylist to print out and the sorted arraylist to print out. I wrote a toString method to print out the original and it compiles but does not print. here is my code:
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;
public class DailyTemperature implements Comparable<DailyTemperature>
{
//variables
private Double temperature;
private String day;
//getTemp & setTemp methods
public double getTemp()
{
return temperature;
}
public void setTemp(double newTemp)
{
temperature = newTemp;
}
//getDay & setTEmp methods
public String getDay()
{
return day;
}
public void setDay(String newDay)
{
day = newDay;
}
public DailyTemperature(String day, double temperature)
{
this.day = day;
this.temperature = temperature;
}
public int compareTo(DailyTemperature other)
{
if (temperature < other.temperature) return -1;
if (temperature == other.temperature) return 0;
return 1;
}
public String toString()
{
return("Day of Week" + this.getDay() +
"Temperature" + this.getTemp());
}
}
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class DailyTemperatureList
{
public static void main (String [] args)
{
ArrayList<DailyTemperature> dailytemps = new ArrayList<DailyTemperature>();
dailytemps.add(new DailyTemperature("Mon", 87.1));
dailytemps.add(new DailyTemperature("Tue", 88.3));
dailytemps.add(new DailyTemperature("Wed", 81.2));
dailytemps.add(new DailyTemperature("Thu", 84.0));
dailytemps.add(new DailyTemperature("Fri", 76.3));
}
public static <T extends Comparable<? super T>>
void insertionSort(ArrayList<DailyTemperature> dailytemps)
{
DailyTemperature temp = null;
int position = 0;
//loop from 2nd element on
for (int i = 1; i < dailytemps.size(); i++)
{
temp = dailytemps.get(i);
position = i;
while ( 0 < position && temp.compareTo(dailytemps.get(position - 1 )) < 0)
{
dailytemps.set(position, dailytemps.get(position - 1));
position--;
}
dailytemps.set(position,temp);
}
System.out.println( dailytemps.toString() );
}
}