I have been trying to write a multithreaded quicksort program using java. There are a lot of samples online using ThreadPool
, CountDownLatch
, etc..
However, i want just to use a count to keep count of the number of threads created.
The logic behind the program is:
1. The main thread calls the parallel quicksort method
2. The method partitions the array and check for the number of current threads
3. Spawn new threads for next step using the same parallel method
4. Or use the single normal quicksort method
I have been gaining performance using the parallel way but it isn’t that much. can someone help me to improve the codes?
here is what I’ve done:
class Quicksort extends Thread {
private int arr[];
private int low,high;
public static int numThreads = Runtime.getRuntime().availableProcessors();
public static int count = 0;
public Quicksort(int[] arr, int low, int high){
this.arr = arr;
this.low = low;
this.high = high;
}
public void run(){
parallelQuicksort(arr,low,high);
}
public static void quicksort(int[] arr, int low, int high){
if (high>low){
int i = partition(arr,low,high);
quicksort(arr,low,i-1);
quicksort(arr,i+1,high);
}
}
public static void parallelQuicksort(int[] arr, int low, int high){
if (high>low){
int i = partition(arr,low,high);
if (count < numThreads){
count++;
Quicksort quicksort = new Quicksort(arr, low, i-1);
quicksort.start();
try{
quicksort.join();
}
catch (InterruptedException e){}
}
else{
quicksort(arr,low,i-1);
}
if (count < numThreads){
count++;
Quicksort quicksort = new Quicksort(arr, i+1, high);
quicksort.start();
try{
quicksort.join();
}
catch (InterruptedException e){}
}
else{
quicksort(arr,i+1,high);
}
}
}
public static int partition(int[] A, int l,int r)
public static void swap(int[] A,int i,int j)
public static int median(int[] A,int l,int mid,int r)
}
The main class:
public class Test{
public static void main(String[] args) {
//generate random array of size 1000000
long start = System.currentTimeMillis();
Quicksort.quicksort(arr,0,arr.length -1);
System.out.println("Single array sorted in "+(System.currentTimeMillis()-start)+" ms");
start = System.currentTimeMillis();
Quicksort.parallelQuicksort(arr2,0,arr.length -1);
System.out.println("Threaded array sorted in "+(System.currentTimeMillis()-start)+" ms");
}
}
The sample output i am getting:
Single array sorted in 393 ms
Threaded array sorted in 367 ms
Single array sorted in 325 ms
Threaded array sorted in 305 ms
Single array sorted in 344 ms
Threaded array sorted in 320 ms