我有一个程序的三类,它们获取一堆数据并使用比较器对其进行排序。我所做的是在名为 EarthquakeDataSet 的类的末尾添加了一个合并排序。合并添加了一个与整数数组一起使用的合并。我想做的是使用来自 EarthquakeRecord 的一系列参考资料。然后我也需要比较才能使用它。合并开始于类 EarthquakeDataSet 的私有 int[] 数据的末尾。任何建议,将不胜感激
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class EarthquakeTest {
public static void main(String[] args) {
EarthquakeDataSet eqds = new EarthquakeDataSet();
String sFileName = null;
try {
File file;
JFileChooser fc = new JFileChooser(".");
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fc.getSelectedFile();
long lElapseTime = eqds.loadDataFromFile(file);// open file and parse all data into <i>EarthquakeRecord</i> objects
System.out.println("File Loading / Parsing: Elapsed time: " + ((float) lElapseTime) / 1000.0);
lElapseTime = eqds.copyOriginalArray();
System.out.println("Create 3 copies of arrays: Elapse Time: " + ((float) lElapseTime) / 1000.0);
eqds.sortNativeJava(); // a batch process akin to the Google batch process of building a planetary index of the internet
System.out.println("Data After Sorting with Native Java Sort");
while (JOptionPane.showConfirmDialog(null, "Display Sorted View?") == 0)
eqds.display(); // allow user to view the data multiple times and view the outcome of the sort: akin to Google users performing lookups
}
} catch (FileNotFoundException fnfe) {
JOptionPane.showMessageDialog(null, "File not found: " + sFileName);
} catch (IOException ioe) {
JOptionPane.showMessageDialog(null, "IO Exception: " + sFileName);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR: General Exception");
e.printStackTrace();
}
}
}
import java.util.Comparator;
public class EarthquakeRecord {
private int nYear;
private int nMonth;
private int nDay;
private int nHour;
private int nMinute;
private double dSecond;
private int nUTC;
private double dLatitude;
private double dLongitude;
private double dMagnitude;
private int nDepth;
private int nEpicentre;
private double dCityLatitude;
private double dCityLongitude;
private String sCityName;
public EarthquakeRecord(String sRawRecord) { parseStringInput(sRawRecord); }
private void parseStringInput(String sRawRecord) {
try {
nYear = Integer.parseInt(sRawRecord.substring(0, 4));
} catch (java.lang.NumberFormatException e) {
nYear = 0;
}
try {
nMonth = Integer.parseInt((sRawRecord.substring(5, 7)).trim());
} catch (java.lang.NumberFormatException e) {
nMonth = 0;
}
try {
nDay = Integer.parseInt((sRawRecord.substring(8, 10)).trim());
} catch (java.lang.NumberFormatException e) {
nDay = 0;
}
try {
nHour = Integer.parseInt((sRawRecord.substring(11, 13)).trim());
} catch (java.lang.NumberFormatException e) {
nHour = 0;
}
try {
nMinute = Integer.parseInt((sRawRecord.substring(14, 16)).trim());
} catch (java.lang.NumberFormatException e) {
nMinute = 0;
}
try {
dSecond = Double.parseDouble((sRawRecord.substring(17, 21)).trim());
} catch (java.lang.NumberFormatException e) {
dSecond = 0.0;
}
try {
nUTC = Integer.parseInt((sRawRecord.substring(23, 25)).trim());
} catch (java.lang.NumberFormatException e) {
nUTC = 0;
}
try {
dLatitude = Double.parseDouble((sRawRecord.substring(30, 37)).trim());
} catch (java.lang.NumberFormatException e) {
dLatitude = 0.0;
}
try {
dLongitude = Double.parseDouble((sRawRecord.substring(38, 46)).trim());
} catch (java.lang.NumberFormatException e) {
dLongitude = 0.0;
}
try {
dMagnitude = Double.parseDouble((sRawRecord.substring(46, 49)).trim());
} catch (java.lang.NumberFormatException e) {
dMagnitude = 0.0;
}
try {
nDepth = Integer.parseInt((sRawRecord.substring(50, 54)).trim());
} catch (java.lang.NumberFormatException e) {
nDepth = 0;
}
try {
nEpicentre = Integer.parseInt((sRawRecord.substring(56, 61)).trim());
} catch (java.lang.NumberFormatException e) {
nEpicentre = 0;
}
try {
dCityLatitude = Double.parseDouble((sRawRecord.substring(62, 71)).trim());
} catch (java.lang.NumberFormatException e) {
dCityLatitude = 0.0;
}
try {
dCityLongitude = Double.parseDouble((sRawRecord.substring(72, 81)).trim());
} catch (java.lang.NumberFormatException e) {
dCityLongitude = 0.0;
}
sCityName = sRawRecord.substring(93, 124).trim();
}
public int getYear() { return nYear; }
public int getMonth() { return nMonth; }
public int getDay() { return nDay; }
public int getHour() { return nHour; }
public int getMinute() { return nMinute; }
public double getSecond() { return dSecond; }
public int getUTC() { return nUTC; }
public double getLatitude() { return dLatitude; }
public double getLongitude() { return dLongitude; }
public double getMagnitude() { return dMagnitude; }
public int getDepth() { return nDepth; }
public int getEpicentre() { return nEpicentre; }
public double getCityLatitude() { return dCityLatitude; }
public double getCityLongitude() { return dCityLongitude; }
public String getCityName() { return sCityName; }
public String toString() {
return String.format("%4d/%2d/%2d %2d:%2d:%2.1f %d Lat/Long:%6.2f,%6.2f Mag:%3.1f Depth:%4d %5d %6.2f:%6.2f %s", nYear, nMonth, nDay, nHour, nMinute, dSecond, nUTC, dLatitude, dLongitude,
dMagnitude, nDepth, nEpicentre, dCityLatitude, dCityLongitude, sCityName);
}
public static class CompareMagnitude implements Comparator<EarthquakeRecord> {
public final static CompareMagnitude instance = new CompareMagnitude();
public int compare(EarthquakeRecord arg0, EarthquakeRecord arg1) {
if(arg0.dMagnitude < arg1.dMagnitude){
return(-1);
}
else if(arg0.dMagnitude > arg1.dMagnitude){
return(1);
}
else{
return(0);
}
}
}
/** Singleton public static inner class that creates a <i>Comparator</i> object if needed; used to compare <i>EarthquakeRecord</i> objects based on <i>String</i> containing City Name */
// TODO implement the following class
public static class CompareCity implements Comparator<EarthquakeRecord> {
public final static CompareCity instance = new CompareCity();
public int compare(EarthquakeRecord arg0, EarthquakeRecord arg1) {return arg0.sCityName.compareTo(arg1.sCityName);}
}
/** Singleton public static inner class that creates a <i>Comparator</i> object if needed; used to compare <i>EarthquakeRecord</i> objects based on <i>nDepth</i> */
// TODO implement the following class
public static class CompareDepth implements Comparator<EarthquakeRecord> {
public final static CompareDepth instance = new CompareDepth();
public int compare(EarthquakeRecord arg0, EarthquakeRecord arg1) {
if(arg0.nDepth < arg1.nDepth){
return(-1);
}
else if(arg0.nDepth > arg1.nDepth){
return(1);
}
else{
return(0);
}
}
}}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class EarthquakeDataSet<aeqrDepthSort> {
private int nNumRecordsLoaded;
private EarthquakeRecord[] aeqrOriginalOrder;
private EarthquakeRecord[] aeqrCitySort;
private EarthquakeRecord[] aeqrDepthSort;
private EarthquakeRecord[] aeqrMagnitudeSort;
public EarthquakeDataSet() { }
public long loadDataFromFile(File file) throws FileNotFoundException, Exception {
Scanner scanInput = new Scanner(file);
int nMaxNumRecords;
do {
nMaxNumRecords = Integer.parseInt(JOptionPane.showInputDialog("Maximum Number of Records: "));
} while (nMaxNumRecords <= 0);
nNumRecordsLoaded = 0;
long lStartTime = System.currentTimeMillis();
aeqrOriginalOrder = new EarthquakeRecord[nMaxNumRecords];
try {
while (nNumRecordsLoaded < nMaxNumRecords && scanInput.hasNext()) {
String sRawRecord = scanInput.nextLine();
aeqrOriginalOrder[nNumRecordsLoaded++] = new EarthquakeRecord(sRawRecord);
}
} catch (Exception e) {
throw new Exception("Input failure at record: " + nNumRecordsLoaded);
} finally {
scanInput.close();
}
System.out.printf("Number Records Loaded: %d", nNumRecordsLoaded);
return System.currentTimeMillis() - lStartTime;
}
public long copyOriginalArray() {
long lStartTime = System.currentTimeMillis();
aeqrCitySort = Arrays.copyOf(aeqrOriginalOrder, aeqrOriginalOrder.length);
aeqrMagnitudeSort = Arrays.copyOf(aeqrOriginalOrder, aeqrOriginalOrder.length);
aeqrDepthSort = Arrays.copyOf(aeqrOriginalOrder, aeqrOriginalOrder.length);
return System.currentTimeMillis() - lStartTime;
}
public void sortNativeJava() {
System.out.println("\nSorting with native Java Sort");
long lStartTime = System.currentTimeMillis();
Arrays.sort(aeqrCitySort, EarthquakeRecord.CompareCity.instance);
long lElapseTime = System.currentTimeMillis() - lStartTime;
System.out.println("Native Java Sort: City Name: Elapsed time: " + ((float) lElapseTime) / 1000.0);
lStartTime = System.currentTimeMillis();
Arrays.sort(aeqrDepthSort, EarthquakeRecord.CompareDepth.instance);
lElapseTime = System.currentTimeMillis() - lStartTime;
System.out.println("Native Java Sort: Depth: Elapsed time: " + ((float) lElapseTime) / 1000.0);
lStartTime = System.currentTimeMillis();
Arrays.sort(aeqrMagnitudeSort, EarthquakeRecord.CompareMagnitude.instance);
lElapseTime = System.currentTimeMillis() - lStartTime;
System.out.println("Native Java Sort: Magnitude: Elapsed time: " + ((float) lElapseTime) / 1000.0);
}
public void display() {
String[] asSortKeys = { "Original", "City Name", "Magnitude", "Depth" };
String sReturnValue = (String) JOptionPane.showInputDialog(null, "Select array to sequence display:", "Key Sequence", JOptionPane.INFORMATION_MESSAGE, null, asSortKeys, asSortKeys[0]);
if (sReturnValue == asSortKeys[0])
display("Original Sequence", aeqrOriginalOrder);
else if (sReturnValue == asSortKeys[1])
display("City Name Sequence", aeqrCitySort);
else if (sReturnValue == asSortKeys[2])
display("Magnitude Sequence", aeqrMagnitudeSort);
else
display("Depth Sequence", aeqrDepthSort);
}
private void display(String rsLabel, EarthquakeRecord[] raeqrDataSet) {
if (raeqrDataSet == null) {
JOptionPane.showMessageDialog(null, "Error: Selected array not yet populated.");
return;
}
System.out.println(rsLabel);
if (nNumRecordsLoaded < 30)
for (int i = 0; i < nNumRecordsLoaded; ++i)
System.out.println(raeqrDataSet[i]);
else {
System.out.println("First 10 records:");
for (int i = 0; i < 10; ++i)
System.out.println(raeqrDataSet[i]);
System.out.println("Middle 10 records:");
int nStart = nNumRecordsLoaded / 2 - 5;
int nEnd = nStart + 10;
for (int i = nStart; i < nEnd; ++i)
System.out.println(raeqrDataSet[i]);
System.out.println("Last 10 records:");
for (int i = nNumRecordsLoaded - 10; i < nNumRecordsLoaded; ++i)
System.out.println(raeqrDataSet[i]);
}
}
public String toString1() { return "Number of Records: " + nNumRecordsLoaded; }
private int[] data;
private static final Random generator = new Random();
public MergeSort( int size )
{
data = new int[ size ];
for ( int i = 0; i < size; i++ )
data[ i ] = 10 + generator.nextInt( 90 );
}
public void sort()
{
sortArray( 0, data.length - 1 );
}
private void sortArray( int low, int high )
{
if ( ( high - low ) >= 1 )
{
int middle1 = ( low + high ) / 2;
int middle2 = middle1 + 1;
System.out.println( "split: " + subarray( low, high ) );
System.out.println( " " + subarray( low, middle1 ) );
System.out.println( " " + subarray( middle2, high ) );
System.out.println();
sortArray( low, middle1 );
sortArray( middle2, high );
merge ( low, middle1, middle2, high );
}
}
private void merge( int left, int middle1, int middle2, int right )
{
int leftIndex = left;
int rightIndex = middle2;
int combinedIndex = left;
int[] combined = new int[ data.length ];
System.out.println( "merge: " + subarray( left, middle1 ) );
System.out.println( " " + subarray( middle2, right ) );
while ( leftIndex <= middle1 && rightIndex <= right )
{
if ( data[ leftIndex ] <= data[ rightIndex ] )
combined[ combinedIndex++ ] = data[ leftIndex++ ];
else
combined[ combinedIndex++ ] = data[ rightIndex++ ];
}
if ( leftIndex == middle2 )
while ( rightIndex <= right )
combined[ combinedIndex++ ] = data[ rightIndex++ ];
else
while ( leftIndex <= middle1 )
combined[ combinedIndex++ ] = data[ leftIndex++ ];
for ( int i = left; i <= right; i++ )
data[ i ] = combined[ i ];
System.out.println( " " + subarray( left, right ) );
System.out.println();
}
public String subarray( int low, int high )
{
StringBuilder temporary = new StringBuilder();
for ( int i = 0; i < low; i++ )
temporary.append( " " );
for ( int i = low; i <= high; i++ )
temporary.append( " " + data[ i ] );
return temporary.toString();
}
public String toString()
{
return subarray( 0, data.length - 1 );
}
}