View on GitHub

justincode

Home Review Ticket and Links Tech Talk Notes Week 1 (Linked List) Week 2 (Calculator) Week 3 (Sorts) Study Week 1

Sorts!

Analysis

Bubble Sort

Selection Sort

Insertion Sort

Merge Sort

Highlights of Work

In this coding assignment, I made use of Runnable

public class Sorts implements Runnable {

And inheritance

public class InsertionSort extends Sorts implements Runnable {

This required the implementation of a “public void run()” function so that the runnable thread can be stored and run in a hashmap.

public void run() {
        int sum=0, time=0, TIMES=12, SIZE=5000;

        for(int i=0; i< TIMES; i++) {
            InsertionSort s = new InsertionSort(SIZE);
            for(int j = 0; j<s.getData().size(); j++) {
                // To see data, uncomment next line
                // System.out.println(s.getData());
                sum += s.getData().get(j);
            }
            System.out.println("Average random: " + sum / ((i+1)*SIZE));
            System.out.println("Average time: " + s.getTimeElapsed());
            System.out.println(s.getSwaps());
            time += s.getTimeElapsed();
        }
        System.out.println("Average random: " + sum / (TIMES*SIZE));
        System.out.println("Total Nanoseconds: " + time );
        System.out.println("Total Seconds: " + time /1000000000.0);
    }

using Instant.now() before and after the algorithm to store the beginning and ending times allowed us to calculate how long it took

Instant start = Instant.now();  // time capture -- start
        // build an array
        for (int i = 0; i < size; i++) {
            data.add((int)(Math.random() * (size+1)));
        }
        // use Inheritance and Polymorphism to replace data.sort with your own algorithm
        int arraySize = data.size();
        for (int i = 1; i < arraySize; i++) {
            int value = data.get(i);
            int index = i - 1;
            while (index >= 0 && data.get(index) > value) {
                data.set(index + 1, data.get(index));
                this.swaps++;
                index--;
            }
            data.set(index + 1, value);
        }
        Instant end = Instant.now();    // time capture -- end
        this.timeElapsed = Duration.between(start, end);