Skip to content

Instantly share code, notes, and snippets.

@dmelcer9
Last active August 26, 2015 01:21
Show Gist options
  • Save dmelcer9/bbef40368de9dc0297cc to your computer and use it in GitHub Desktop.
Save dmelcer9/bbef40368de9dc0297cc to your computer and use it in GitHub Desktop.
A RecursiveTask Quicksort
import java.util.*;
import java.util.concurrent.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class RecursiveQuicksort {
static int listLength = 1000000;
public static void main(String[] args) {
LinkedList<Integer> unsortedList= new LinkedList<>();
Random r = new Random();
for(int i = 0;i<listLength;i++) unsortedList.add(r.nextInt(1000000)); //Fill the list randomly
System.out.println("List created");
//Invokes a quickSortFork
//Note that the lambda expression defines the Comparator<Integer>
List<Integer> sortedList = new quickSortFork<Integer, LinkedList<Integer>>(unsortedList, (i,j)->(i-j)).invoke();
System.out.println("Done, now printing...");
System.out.println(sortedList); //This will take a long time to print
}
public static class quickSortFork<T,V extends List<T>> extends RecursiveTask<V>{
V inputArray; //Stores the array that is passed as a parameter
Comparator<T> comparator; //Used to determine sort order
public quickSortFork(V inputArray, Comparator<T> comparator){
this.inputArray = inputArray;
this.comparator= comparator;
}
protected V compute(){
if (inputArray.size()<=1){
return inputArray; //Can't sort the array any further
}
T pivot = inputArray.get(0); //Arbitrarily chosen
V lessThan = getNewInstance(); //Stores x<pivot
V equals = getNewInstance(); //Stores x=pivot
V moreThan = getNewInstance(); //Stores x>pivot
for(T current: inputArray){
//Determine where to put current
int result = comparator.compare(current, pivot);
if (result<0) lessThan.add(current);
else if(result > 0) moreThan.add(current);
else equals.add(current);
}
V outputArray = getNewInstance();
//Create new fork objects
quickSortFork<T,V> lowerOutput = new quickSortFork<>(lessThan, comparator);
quickSortFork<T,V> higherOutput = new quickSortFork<>(moreThan, comparator);
higherOutput.fork(); //Start computation of higherOutput
outputArray.addAll(lowerOutput.compute()); //Get lowerOutput sorted
outputArray.addAll(equals);
outputArray.addAll(higherOutput.join()); //Wait for higherOutput to finish, then add
return outputArray;
}
//Hacky workaround because java doesn't allow creation of generics
protected V getNewInstance(){
try {
return (V) inputArray.getClass().newInstance();
} catch (InstantiationException ex) {
Logger.getLogger(RecursiveQuicksort.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(RecursiveQuicksort.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment