diff --git a/Sorting/BubbleSorter.java b/Sorting/BubbleSorter.java index d1995ad..f89123d 100644 --- a/Sorting/BubbleSorter.java +++ b/Sorting/BubbleSorter.java @@ -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;i0){ + swap(numbers[i],numbers[i+1]); + usedSwap=true; + } + } + }while(usedSwap); + } + } \ No newline at end of file diff --git a/Sorting/RandomNumberFileReader.java b/Sorting/RandomNumberFileReader.java index ddbd925..53f33d5 100644 --- a/Sorting/RandomNumberFileReader.java +++ b/Sorting/RandomNumberFileReader.java @@ -1,5 +1,33 @@ package Sorting; -public class RandomNumberFileReader { - -} \ No newline at end of file +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 numbers = new ArrayList(); + + 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 getNumbers(){ + return numbers; + } + + +} diff --git a/Sorting/Sorter.java b/Sorting/Sorter.java index 968fc56..f217b44 100644 --- a/Sorting/Sorter.java +++ b/Sorting/Sorter.java @@ -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; + } } \ No newline at end of file