51 lines
1.3 KiB
Java
51 lines
1.3 KiB
Java
package Sorting;
|
|
|
|
import java.time.Duration;
|
|
import java.time.Instant;
|
|
import java.lang.Integer;
|
|
|
|
/**
|
|
* This is an abstract class, its subclasses will inherit its methods and instance
|
|
* fields. Any abstract methods will have to be implemented in the subclasses.
|
|
*/
|
|
abstract class Sorter {
|
|
|
|
protected Integer[] numbers;
|
|
protected long swapsUsed = 0;
|
|
protected long comparisonsUsed = 0;
|
|
|
|
public Sorter(String filename){
|
|
RandomNumberFileReader reader = new RandomNumberFileReader(filename);
|
|
reader.getNumbers().toArray(numbers);
|
|
}
|
|
|
|
/**
|
|
* An abstract sorting method. Each subclass will have to implement its own
|
|
* version of this method.
|
|
* @return A SortResult object holding number of comparisons, number of swaps, and the sorted array
|
|
*/
|
|
abstract void sort();
|
|
|
|
void swap(int a, int b){
|
|
swapsUsed++;
|
|
int tmp = a;
|
|
a = b;
|
|
b = tmp;
|
|
}
|
|
|
|
int compare(int a, int b){
|
|
comparisonsUsed++;
|
|
return Integer.compare(a,b);
|
|
}
|
|
|
|
public SortResult measuredSort(){
|
|
Instant start = Instant.now();
|
|
this.sort();
|
|
Instant end = Instant.now();
|
|
Duration time = Duration.between(start,end);
|
|
SortResult output = new SortResult(numbers, comparisonsUsed, swapsUsed, time);
|
|
return output;
|
|
}
|
|
|
|
|
|
} |