summaryrefslogtreecommitdiff
path: root/labs/lab08_gnome_sort/SortingFrame.java
blob: 6ceb49eec36af3729b157972f37f8bced4485e92 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
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;
	}
}