From 6eda47cf6c4e7546e8e915d1e7ba60af6eaae9d6 Mon Sep 17 00:00:00 2001 From: Daniel Date: Fri, 21 Aug 2020 16:08:36 -0500 Subject: [PATCH] Removed some unneccessary lines of code started to fix up --- .../algorithmvisualizer/AlgVisualizer.java | 96 +++---------- .../algorithmvisualizer/ArrDisplay.java | 15 +- .../algorithmvisualizer/ArrSorting.java | 131 ++++-------------- 3 files changed, 48 insertions(+), 194 deletions(-) diff --git a/src/com/example/algorithmvisualizer/AlgVisualizer.java b/src/com/example/algorithmvisualizer/AlgVisualizer.java index 97ee297..9fd5c0d 100644 --- a/src/com/example/algorithmvisualizer/AlgVisualizer.java +++ b/src/com/example/algorithmvisualizer/AlgVisualizer.java @@ -26,9 +26,8 @@ public class AlgVisualizer implements ActionListener, ChangeListener { private final int CONTENT_WIDTH = 900; - private final int CONTENT_HEIGHT = 960; private final int ARR_DISPLAY_HEIGHT = 900; - private final int FPS_MIN = 1; + private final int FPS_MIN = 2; private final int FPS_INIT = 10; private final int FPS_MAX = 100; private final String[] SIZE_OPTIONS = { "10", "50", "100", "300", "450", "900" }; // array size options @@ -38,7 +37,6 @@ public class AlgVisualizer implements ActionListener, ChangeListener { private long totalDelay; private Integer indexComparisons; private long startTime; // start time of a sort - private long endTime; // end time of a sort private long visualizationTime; private long sortingTime; private boolean doBubbleSort; @@ -74,11 +72,7 @@ public static void main(String[] args) { algVisualizer.initializeVars(); algVisualizer.setFrame(); } - - public AlgVisualizer() { - // empty constructor, variables are initialized in main method. - } - + /* * This method initializes all of this classes instance variables. The array is * initialized, filled, and shuffled. The arrDisplay object that paints the @@ -88,21 +82,13 @@ public AlgVisualizer() { */ public void initializeVars() { - setN(10); - - arr = new Integer[n]; - arr = fillArr(arr); - arr = shuffleArr(arr); + n = Integer.parseInt(SIZE_OPTIONS[0]); + arr = initArr(); indexComparisons = 0; - startTime = 0; - endTime = 0; - visualizationTime = 0; - sortingTime = 0; setDelay(1000 / FPS_INIT); // Initialize objects that will display and sort the array - arrDisplay = new ArrDisplay(this); arrDisplay.setArr(arr); arrDisplay.setPreferredSize(new Dimension(CONTENT_WIDTH, ARR_DISPLAY_HEIGHT)); @@ -111,7 +97,6 @@ public void initializeVars() { // Panels in the frame that will hold all components. // JPanels use the flowLayout to manage their components automatically. - buttonPanel = new JPanel(); buttonPanel.setBackground(Color.DARK_GRAY); @@ -119,7 +104,6 @@ public void initializeVars() { arrPanel.add(arrDisplay); // Initialize all components and add action listeners - resetButton = new JButton("Reset"); resetButton.addActionListener(this); resetButton.setBackground(Color.WHITE); @@ -152,7 +136,6 @@ public void initializeVars() { FPSslider.addChangeListener(this); FPSslider.setBackground(Color.DARK_GRAY); // Initialize the performance label and center it - performanceLabel = new JLabel(); performanceLabel.setHorizontalAlignment(SwingConstants.CENTER); } @@ -163,7 +146,6 @@ public void initializeVars() { * JFrame. The frame is initialized and made visible. */ public void setFrame() { - // Add JButtons / components to button panel buttonPanel.add(resetButton); buttonPanel.add(bubbleButton); @@ -173,7 +155,6 @@ public void setFrame() { buttonPanel.add(quickButton); buttonPanel.add(sizeChanger); buttonPanel.add(FPSslider); - // Initialize and make the frame visible frame = new JFrame("Algorithm Visualizer"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); @@ -184,7 +165,6 @@ public void setFrame() { frame.pack(); frame.setLocationRelativeTo(null); // center of the screen frame.setVisible(true); - } /* @@ -204,7 +184,6 @@ public void actionPerformed(ActionEvent event) { doInsertionSort = false; doMergeSort = false; doQuickSort = false; - // Find the source of the action if (event.getSource() == bubbleButton) { doBubbleSort = true; @@ -227,12 +206,7 @@ public void actionPerformed(ActionEvent event) { } else if (event.getSource() == sizeChanger) { // Find what size was selected, and set n to that value String selectedSize = (String) sizeChanger.getSelectedItem(); - setN(Integer.valueOf(selectedSize)); - - // Create the new array of length n, and it will be shuffled in reset() - arr = new Integer[n]; - arr = fillArr(arr); - + n = Integer.valueOf(selectedSize); // reset and paint the new array reset(); arrSort.execute(); @@ -258,12 +232,12 @@ public void stateChanged(ChangeEvent e) { * SwingWorker, we simply re-instantiate it so that we are able to call it * again. */ + public void reset() { setStopSort(true); - arr = shuffleArr(arr); + arr = initArr(); arrDisplay.clearSwappedIndexes(); arrDisplay.setComplete(false); - arrDisplay.setArr(arr); indexComparisons = 0; resetTime(); resetSwingWorker(this, arr, arrDisplay); @@ -278,11 +252,17 @@ public void resetSwingWorker(AlgVisualizer alg, Integer[] arr, ArrDisplay displa // method public void resetTime() { startTime = 0; - endTime = 0; visualizationTime = 0; sortingTime = 0; totalDelay = 0; } + + public Integer[] initArr() { + Integer[] arr = new Integer[n]; + arr = fillArr(arr); + arr = shuffleArr(arr); + return arr; + } public Integer[] shuffleArr(Integer[] arr) { arr = fillArr(arr); @@ -312,24 +292,20 @@ public Integer[] fillArr(Integer[] arr) { */ public void updatePerformance() { numSwaps = arrDisplay.getSwappedIndexes().size(); - System.out.println("total delay " + totalDelay); - if (!getSort().equals("Not Sorting") && arrDisplay.getNumChunks() == 1) { + if (!getSort().equals("Not Sorting") && arrDisplay.getNumChunks() == 0) { visualizationTime = System.currentTimeMillis() - startTime; sortingTime = visualizationTime - totalDelay; - } else if (arrDisplay.getNumChunks() > 1) { + } else if (arrDisplay.getNumChunks() > 1 && !arrDisplay.isComplete()) { visualizationTime = System.currentTimeMillis() - startTime; sortingTime = visualizationTime - totalDelay; } if(stopSort) { resetTime(); } - String performance = String.format( "Index Comparisons : %d Index Swaps : %d Visualization Time : %dms Sorting Time : %dms", indexComparisons, numSwaps, visualizationTime, sortingTime); - performanceLabel.setText(performance); - frame.pack(); } @@ -341,10 +317,6 @@ public int getArrDispHeight() { return ARR_DISPLAY_HEIGHT; } - public int getHeight() { - return CONTENT_HEIGHT; - } - public int getWidth() { return CONTENT_WIDTH; } @@ -417,14 +389,6 @@ public void setStopSort(boolean toSet) { stopSort = toSet; } - public int getN() { - return n; - } - - public void setN(int n) { - this.n = n; - } - public Integer getIndexComparisons() { return indexComparisons; } @@ -433,30 +397,10 @@ public void setIndexComparisons(int indexComparisons) { this.indexComparisons = indexComparisons; } - public long getStartTime() { - return startTime; - } - public void setStartTime(long startTime) { this.startTime = startTime; } - public long getEndTime() { - return endTime; - } - - public void setEndTime(long endTime) { - this.endTime = endTime; - } - - public JLabel getPerformanceLabel() { - return performanceLabel; - } - - public void setPerformanceLabel(JLabel performanceLabel) { - this.performanceLabel = performanceLabel; - } - public int getNumSwaps() { return numSwaps; } @@ -473,14 +417,6 @@ public void setDelay(int delay) { this.delay = delay; } - public JSlider getFPSslider() { - return FPSslider; - } - - public void setFPSslider(JSlider fPSslider) { - FPSslider = fPSslider; - } - public long getTotalDelay() { return totalDelay; } diff --git a/src/com/example/algorithmvisualizer/ArrDisplay.java b/src/com/example/algorithmvisualizer/ArrDisplay.java index f7ec896..331a130 100644 --- a/src/com/example/algorithmvisualizer/ArrDisplay.java +++ b/src/com/example/algorithmvisualizer/ArrDisplay.java @@ -50,33 +50,23 @@ public ArrDisplay(AlgVisualizer algVisualizer) { */ @Override public void paintComponent(Graphics g) { - // Takes ~ 40ms to draw ( depending on the system ) Graphics2D graphics2d = (Graphics2D) g; - // Draw the DARK_GREY background graphics2d.setColor(Color.DARK_GRAY); graphics2d.fillRect(0, 0, algVisualizer.getWidth(), algVisualizer.getArrDispHeight()); - - // Find the values of the swappedIndexes and update framesPainted if (algVisualizer.getSort().equals("Not Sorting") || isComplete) { swappedIndex1 = -1; swappedIndex2 = -1; } else if (!algVisualizer.stopSort()) { // exclude the first chunk as its used to draw the first array, not related to the sorting - swappedIndex1 = swappedIndexes.get(numChunks - 1)[0]; // index out of bounds exception? - swappedIndex2 = swappedIndexes.get(numChunks - 1)[1]; + swappedIndex1 = swappedIndexes.get(numChunks)[0]; // index out of bounds exception? + swappedIndex2 = swappedIndexes.get(numChunks)[1]; } - // Iterate through the array and drawn every index for (int i = 0; i < arr.length; i++) { - - // Dimensions of the bars are calculated to make sure they take up the entire - // Panel int width = (int) (algVisualizer.getWidth() / (double) arr.length); int height = arr[i] * (algVisualizer.getArrDispHeight() / arr.length); int x = i * width; int y = algVisualizer.getArrDispHeight() - height; - - // Determine the colour of the bar we are currently drawing if (i == swappedIndex1 && !algVisualizer.stopSort()) { graphics2d.setColor(Color.RED); } else if (i == swappedIndex2 && !algVisualizer.stopSort()) { @@ -86,7 +76,6 @@ public void paintComponent(Graphics g) { } else { graphics2d.setColor(Color.WHITE); } - // Draw the current indexes bar graphics2d.fillRect(x, y, width, height); } diff --git a/src/com/example/algorithmvisualizer/ArrSorting.java b/src/com/example/algorithmvisualizer/ArrSorting.java index cecdb6e..809be22 100644 --- a/src/com/example/algorithmvisualizer/ArrSorting.java +++ b/src/com/example/algorithmvisualizer/ArrSorting.java @@ -42,25 +42,25 @@ public ArrSorting(AlgVisualizer algVisualizer, Integer[] arr, ArrDisplay arrDisp */ @Override protected Void doInBackground() throws Exception { + // COULD BE MORE DRY ? if (algVisualizer.stopSort()) { publish(arr.clone()); sleep(); algVisualizer.resetSwingWorker(algVisualizer, arr, arrDisplay); } else { algVisualizer.setStartTime(System.currentTimeMillis()); + if (algVisualizer.getSort().equals("Bubble Sort")) { + bubbleSort(); + } else if (algVisualizer.getSort().equals("Insertion Sort")) { + insertionSort(); + } else if (algVisualizer.getSort().equals("Selection Sort")) { + selectionSort(); + } else if (algVisualizer.getSort().equals("Merge Sort")) { + mergeSort(0, arr.length - 1); + } else if (algVisualizer.getSort().equals("Quick Sort")) { + quickSort(0, arr.length - 1); + } } - if (algVisualizer.getSort().equals("Bubble Sort")) { - bubbleSort(); - } else if (algVisualizer.getSort().equals("Insertion Sort")) { - insertionSort(); - } else if (algVisualizer.getSort().equals("Selection Sort")) { - selectionSort(); - } else if (algVisualizer.getSort().equals("Merge Sort")) { - mergeSort(0, arr.length - 1); - } else if (algVisualizer.getSort().equals("Quick Sort")) { - quickSort(0, arr.length - 1); - } - algVisualizer.setEndTime(System.currentTimeMillis()); return null; } @@ -84,20 +84,15 @@ protected Void doInBackground() throws Exception { */ @Override protected void process(List chunks) { - while (chunks.size() > 0) { - // Paint each cloned array and update number of chunks - numChunks++; - arrDisplay.setNumChunk(this.numChunks); - arrDisplay.setArr(chunks.get(0)); + for (int i = 0; i < chunks.size(); i++) { + // Paint each cloned array that was sent as a chunk + arrDisplay.setNumChunk(numChunks++); + arrDisplay.setArr(chunks.get(i)); arrDisplay.repaint(); - chunks.remove(0); } } - /* - * The amount of time this thread waits after sending a chunk to be drawn in the - * Event Dispatch Thread - */ + // The amount of time this thread waits after sending a chunk to be drawn private void sleep() { try { Thread.sleep(algVisualizer.getDelay()); @@ -110,37 +105,28 @@ private void sleep() { private void bubbleSort() { for (int i = 0; i < n - 1; i++) { - // If sorting has been stopped, don't sort - if (algVisualizer.stopSort()) { + if (algVisualizer.stopSort()) break; - } for (int j = 0; j < n - i - 1; j++) { - // If sorting has been stopped, don't sort if (algVisualizer.stopSort()) { break; } else { - // Add a comparison algVisualizer.setIndexComparisons(algVisualizer.getIndexComparisons() + 1); - - if (arr[j] > arr[j + 1]) { // comparison - + if (arr[j] > arr[j + 1]) { // swap arr[j] and arr[j+1] int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; // Add the pair of indexes that were swapped to the list. arrDisplay.addSwappedIndexes(j, j + 1); - // Repaint the new array. publish(arr.clone()); sleep(); } } } } - // If sorting hasn't been stopped, set end time, complete and draw one more - // time. + // Sorting complete, loop done if (!algVisualizer.stopSort()) { - algVisualizer.setEndTime(System.currentTimeMillis()); arrDisplay.setComplete(true); publish(arr.clone()); sleep(); @@ -148,32 +134,24 @@ private void bubbleSort() { } private void selectionSort() { - for (int i = 0; i < n - 1; i++) { - // If sorting has been stopped, don't sort - if (algVisualizer.stopSort()) { + if (algVisualizer.stopSort()) break; - } - int min_idx = i; - for (int j = i + 1; j < n; j++) { - // Add a comparison algVisualizer.setIndexComparisons(algVisualizer.getIndexComparisons() + 1); - - if (arr[j] < arr[min_idx]) // comparison + if (arr[j] < arr[min_idx]) min_idx = j; } + // Swap arr[min_idx] and arr[i] int temp = arr[min_idx]; arr[min_idx] = arr[i]; arr[i] = temp; // Add a pair of swapped indexes arrDisplay.addSwappedIndexes(min_idx, i); - // Repaint the new array. publish(arr.clone()); sleep(); } - // If sorting hasn't been stopped, set complete and draw one more time. if (!algVisualizer.stopSort()) { arrDisplay.setComplete(true); publish(arr.clone()); @@ -182,39 +160,26 @@ private void selectionSort() { } private void insertionSort() { - for (int i = 1; i < n; ++i) { - // If sorting has been stopped, don't sort - if (algVisualizer.stopSort()) { + if (algVisualizer.stopSort()) break; - } - int key = arr[i]; int j = i - 1; - while (j >= 0 && arr[j] > key) { // compare arr[j] and arr[i] - if (algVisualizer.stopSort()) { - publish(arr.clone()); - sleep(); + if (algVisualizer.stopSort()) break; - } - // Add a comparison algVisualizer.setIndexComparisons(algVisualizer.getIndexComparisons() + 1); - + // swap arr[j] and arr[j + 1] arr[j + 1] = arr[j]; j = j - 1; - // Add a pair of swapped indexes arrDisplay.addSwappedIndexes(j, j + 1); - // Repaint the array publish(arr.clone()); sleep(); } // Add a pair of swapped indexes algVisualizer.setIndexComparisons(algVisualizer.getIndexComparisons() + 1); - arr[j + 1] = key; } - // If sorting hasn't been stopped, set complete and draw one more time. if (!algVisualizer.stopSort()) { arrDisplay.setComplete(true); publish(arr.clone()); @@ -227,11 +192,9 @@ private void mergeSort(int l, int r) { if (l < r) { // Find the middle point int m = (l + r) / 2; - // Sort first and second halves mergeSort(l, m); mergeSort(m + 1, r); - // Merge the sorted halves merge(l, m, r); } @@ -253,75 +216,54 @@ private void merge(int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; - // Create temp arrays int L[] = new int[n1]; int R[] = new int[n2]; - // Copy data to temp arrays for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; - // Merge the temp arrays - // Initial indexes of first and second subarrays int i = 0, j = 0; - // Initial index of merged subarray array int k = l; while (i < n1 && j < n2) { - // If sorting has been stopped, don't merge if (algVisualizer.stopSort()) break; - // Add a comparison algVisualizer.setIndexComparisons(algVisualizer.getIndexComparisons() + 1); - - if (L[i] <= R[j]) { // comparison + if (L[i] <= R[j]) { arr[k] = L[i]; i++; - // Add a pair of swapped indexes arrDisplay.addSwappedIndexes(k, k + i); - // Repaint the array publish(arr.clone()); sleep(); } else { arr[k] = R[j]; j++; - // Add a pair of swapped indexes arrDisplay.addSwappedIndexes(k, k + j); - // Repaint the arrays publish(arr.clone()); sleep(); } k++; } - /* Copy remaining elements of L[] if any */ while (i < n1) { - // If sorting has been stopped, don't copy if (algVisualizer.stopSort()) break; - arr[k] = L[i]; - // Add a pair of swapped indexes arrDisplay.addSwappedIndexes(k, k + i); - // Repaint the array publish(arr.clone()); sleep(); i++; k++; } - /* Copy remaining elements of R[] if any */ while (j < n2) { - // If sorting has been stopped, don't copy if (algVisualizer.stopSort()) break; - arr[k] = R[j]; - // Add a pair of swapped indexes arrDisplay.addSwappedIndexes(k, k + j); publish(arr.clone()); sleep(); @@ -342,8 +284,6 @@ private void quickSort(int low, int high) { quickSort(low, pi - 1); quickSort(pi + 1, high); } - // don't think there is another way to know whether or not - // the array is sorted besides this if (isSorted() && !algVisualizer.stopSort()) { arrDisplay.setComplete(true); publish(arr.clone()); @@ -356,39 +296,28 @@ private int partition(int low, int high) { if (algVisualizer.getSort().equals("Quick Sort") && !algVisualizer.stopSort()) { // Needed because of recursion int pivot = arr[high]; int i = (low - 1); // index of smaller element - for (int j = low; j < high; j++) { - if (algVisualizer.getSort().equals("Quick Sort") && !algVisualizer.stopSort()) { // Needed because of - // recursion - // Add a comparison + if (algVisualizer.getSort().equals("Quick Sort") && !algVisualizer.stopSort()) { algVisualizer.setIndexComparisons(algVisualizer.getIndexComparisons() + 1); - // If current element is smaller than the pivot - if (arr[j] < pivot) { // comparison - + if (arr[j] < pivot) { i++; - // swap arr[i] and arr[j] int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; - // Add a pair of swapped indexes arrDisplay.addSwappedIndexes(i, j); - // Repaint the array publish(arr.clone()); sleep(); } } } - if (algVisualizer.getSort().equals("Quick Sort") && !algVisualizer.stopSort()) { // Needed because of - // recursion + if (algVisualizer.getSort().equals("Quick Sort") && !algVisualizer.stopSort()) { // swap arr[i+1] and arr[high] (or pivot) int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; - // Add a pair of swapped indexes arrDisplay.addSwappedIndexes(i + 1, high); - // Repaint the array publish(arr.clone()); sleep(); }