Skip to content

Instantly share code, notes, and snippets.

@FreedomGrenade
Created October 4, 2015 00:57
Show Gist options
  • Save FreedomGrenade/47f0a5f25f7d17777da1 to your computer and use it in GitHub Desktop.
Save FreedomGrenade/47f0a5f25f7d17777da1 to your computer and use it in GitHub Desktop.
import java.util.concurrent.atomic.*;
AtomicInteger threadCount;
int startTime;
int tTime;
int sorts;
int numbers = 100000000;
int[] h;
public void setup() {
size(1000, 100);
tTime = 0;
sorts = 0;
threadCount = new AtomicInteger(0);
sortStart();
}
public void draw() {
background(255);
if (threadCount.get() == 0) {
int dif = millis() -startTime;
println("Succeed ? : " + checkSorted(h));
tTime += dif;
sorts++;
println ("Avg:" + ((float)tTime/sorts) + " Last:" + dif);
sortStart();
} else {
}
}
public void drawit() {
stroke(0);
for (int i = 0; i < width; i++) {
line(i, height, i, height - h[i*(numbers/width)]*height/numbers);
}
}
public void sortStart() {
h = generate(numbers, millis());
startTime = millis();
(new Thread(new Thready(h, 0, h.length-1, threadCount))).start();
}
public class Thready implements Runnable {
int minM, maxM;
int[] h;
AtomicInteger T;
public Thready(int[] h, int min, int max, AtomicInteger at) {
this.h = h;
this.minM = min;
this.maxM = max;
T = at;
}
public void run() {
T.incrementAndGet();
quickSort(h, minM, maxM);
T.decrementAndGet();
}
void quickSort(int[] haystack, int min, int max) {
if (min < max) {
int pivotLoc = part(haystack, min, max);
quickSort(haystack, min, pivotLoc - 1);
if (threadCount.get() < 4) {
(new Thread(new Thready(haystack, pivotLoc + 1, max, T))).start();
//b.start();
} else {
quickSort(haystack, pivotLoc + 1, max);
}
}
}
//http://www.algorithmist.com/index.php/Quicksort --- transalted psuedocode there to java to test
int part(int[] haystack, int min, int max) {
int pivot = haystack[min];
int left = min;
for (int i=min+1; i<=max; i++) {
if (haystack[i] < pivot) {
left++;
int temp = haystack[i] ^ haystack[left];
haystack[i]^=temp; //haystack[left];
haystack[left]^=temp;
}
}
int temp = haystack[min];
haystack[min] = haystack[left];
haystack[left] = temp;
return left;
}
}
//////////
public int[] generate(int n, int seed) {
randomSeed(seed);
int[] h = new int[n];
for (int i = 0; i < n; i++) {
h[i] = (int)random(n);
}
return h;
}
public boolean checkSorted(int[] h) {
for (int i = 0; i < h.length - 1; i++) {
if (h[i] > h[i+1]) return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment