import java.util.Random; import javax.swing.JFrame; public class SortingFrame { public static void main(String[] args) throws InterruptedException { JFrame frame = new JFrame(); int[] data = randomIntArray(40); VisualSortingComponent vsc = new VisualSortingComponent(data); frame.setTitle("Sorting Visualization"); frame.setSize(500,500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(vsc); frame.setVisible(true); Thread.sleep(50); //bubbleSort(data,vsc); gnomeSort(data,vsc); } public static void bubbleSort(int[] data, VisualSortingComponent vsc) throws InterruptedException { int size = data.length; for(int i = 0; i < size; i++) { for(int j = 0; j < size - 1; j++) { if(data[j] > data[j + 1]) { int temp = data[j]; data[j] = data[j + 1]; data[j + 1] = temp; vsc.repaint(); Thread.sleep(10); } } } } public static void gnomeSort(int[] data, VisualSortingComponent vsc) throws InterruptedException { int last = data[0]; for(int i = 1; i < data.length; i++) { //System.out.println("Sorting " + i); if(data[i] < last) { //System.out.println("\tDoing work"); //The data is out of order, do some work int j = i; while(j>0) { if(data[j-1]>data[j]) { //System.out.println("\tSwaping " + (j-1) + " and " + j); data = swap(data,j-1,j); j--; vsc.repaint(); Thread.sleep(10); } else { break; } } } last = data[i]; } } private static int[] swap(int[] data, int ind1, int ind2) { int tmp = data[ind1]; data[ind1] = data[ind2]; data[ind2] = tmp; return data; } public static int[] randomIntArray(int size) { int[] result = new int[size]; for(int i = 1; i <= size; i++) { result[i - 1] = i; } Random rand = new Random(); for(int i = 0; i < size * 100; i++) { int first = rand.nextInt(size); int second = rand.nextInt(size); int temp = result[first]; result[first] = result[second]; result[second] = temp; } return result; } }