test implementation of classes with autoboxing

This commit is contained in:
2020-05-30 10:33:12 -05:00
parent 10662f96d9
commit fbd13aaac3
3 changed files with 85 additions and 4 deletions

View File

@@ -2,4 +2,23 @@ package Sorting;
public class BubbleSorter extends Sorter{
//a class to sort arrays of numbers using bubble sort
public BubbleSorter(String filename){
super(filename);
}
void sort(){
boolean usedSwap;
do{
usedSwap=false;
for(int i=0;i<numbers.length-1;i++){
if(compare(numbers[i],numbers[i+1])>0){
swap(numbers[i],numbers[i+1]);
usedSwap=true;
}
}
}while(usedSwap);
}
}

View File

@@ -1,5 +1,33 @@
package Sorting;
public class RandomNumberFileReader {
}
import java.util.ArrayList;
import java.lang.Integer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.io.BufferedReader;
import java.io.IOException;
class RandomNumberFileReader{
private ArrayList<Integer> numbers = new ArrayList<Integer>();
public RandomNumberFileReader(String file){
//Reads in from a text file of integers, one on each line
try{
BufferedReader reader = Files.newBufferedReader(Path.of(file));
String line = null;
while((line = String.valueOf(reader.readLine()))!=null){
numbers.add(Integer.valueOf(line));
}
reader.close();
} catch (IOException ex){
System.err.println(ex);
}
}
public ArrayList<Integer> getNumbers(){
return numbers;
}
}

View File

@@ -1,17 +1,51 @@
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
*/
public abstract SortResult sort();
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;
}
}