Files
Tutoring-APCompSci/Sorting/Sorter.java

52 lines
1.4 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 String sortType;
protected Integer[] numbers;
protected long comparisonsUsed = 0;
public Sorter(String st, String filename){
sortType=st;
RandomNumberFileReader reader = new RandomNumberFileReader(filename);
numbers = new Integer[reader.getNumbers().size()];
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){
int tmp = numbers[a];
numbers[a] = numbers[b];
numbers[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(sortType, numbers, comparisonsUsed, time);
return output;
}
}