Question
Modify the selection sort programso that it displays 2 graphics, each with a different sorting algorithm sorting a copy of the array. Use selection sort
Modify the selection sort programso that it displays 2 graphics, each with a different sorting algorithm sorting a copy of the array. Use selection sort and bubble sort. Display both algorithms at the same time in one single JFrame (two JPanels). Also add JFilechooser to read the array to be sorted from a txt file called "input.txt" and save the sorted array to another txt file called "output.txt". Instead of buttons, use JMenuItems for the load and save functions. Make sure that the JFilechooser by default opens/saves only txt files. The following is the code that needs to be modified.
import java.awt.BorderLayout; import javax.swing.JButton; import javax.swing.JFrame;
public class SelectionSortViewer { public static void main(String[] args) { JFrame frame = new JFrame(); final int FRAME_WIDTH = 300; final int FRAME_HEIGHT = 400; frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final SelectionSortComponent component = new SelectionSortComponent(); frame.add(component, BorderLayout.CENTER); frame.setVisible(true); component.startAnimation(); } }
import java.awt.color.*; import java.awt.Color; import java.awt.Graphics; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.swing.JComponent; public class SelectionSort { public static void main(String args) { } private int[] a; private int markedPosition = -1; private int alreadySorted = -1; private Lock sortStateLock; private JComponent component; private static final int DELAY = 50; public SelectionSort(int[] anArray, JComponent aComponent) { a = anArray; sortStateLock = new ReentrantLock(); component = aComponent; } public void sort() throws InterruptedException { for(int i=0; i < a.length - 1; i++) { int minPos = minimunPosition(i); sortStateLock.lock(); try { swap(a, minPos, i); alreadySorted = i; } finally { sortStateLock.unlock(); } pause(2); } } public void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } private int minimunPosition(int from) throws InterruptedException { int minPos = from; for(int i = from + 1; i import java.awt.Graphics; import java.util.Random; import javax.swing.JComponent; public class SelectionSortComponent extends JComponent { private SelectionSort sorter; Random s = new Random(); public SelectionSortComponent() { int[] values = new int[30]; for(int i = 0; i
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started