Created
October 18, 2014 22:11
-
-
Save keshavsaharia/2d8614a00598fe16d8de to your computer and use it in GitHub Desktop.
Rainbow Sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import zen.core.Zen; | |
public class RainbowSort { | |
// Just some utility stuff, leave these variables alone. | |
private static boolean visualized = false; | |
private static int size = 500, step = 1; | |
private static int min = 0, max = 0; | |
private static int[] cache; | |
// Creates an array and visualizes the sorting of it. | |
public static void main(String[] args) { | |
} | |
// Randomizes the contents of an array, so you don't have to. The size field adjusts the array | |
// length, and the max field adjusts the maximum value. | |
public static int[] randomArray(int size, int max) { | |
int[] array = new int[size]; | |
for (int i = 0 ; i < array.length ; i++) { | |
array[i] = (int) (Math.random() * max); | |
} | |
return array; | |
} | |
// For visualizing the array. You can keep passing your array to this function, and it will | |
// visually display the array and optionally wait for the given amount of time (default is 30). | |
private static void visualize(int[] array) { | |
visualize(array, 30); | |
} | |
private static void visualize(int[] array, int delay) { | |
if (! visualized) { | |
Zen.create(size, size); | |
while (step * step < array.length) { | |
step++; | |
} | |
visualized = true; | |
cache = new int[array.length]; | |
for (int i = 0 ; i < array.length ; i++) { | |
cache[i] = -1 * array[i]; | |
if (array[i] > max) { | |
max = array[i]; | |
} | |
} | |
} | |
int x = 0; | |
int y = 0; | |
for (int i = 0 ; i < array.length ; i++) { | |
if (cache[i] != array[i]) { | |
int color = 255 * array[i] / max; | |
Zen.setColor(color, color, color); | |
Zen.fillRect(x, y, size / step, size / step); | |
} | |
if ((i + 1) % step == 0) { | |
x = 0; | |
y = y + size / step; | |
} | |
else { | |
x += size / step; | |
} | |
cache[i] = array[i]; | |
} | |
Zen.sleep(delay); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment