Skip to content

Instantly share code, notes, and snippets.

@EliaRohana
Created June 1, 2016 12:40
Show Gist options
  • Select an option

  • Save EliaRohana/25b924048d990c5358313d18daf8f491 to your computer and use it in GitHub Desktop.

Select an option

Save EliaRohana/25b924048d990c5358313d18daf8f491 to your computer and use it in GitHub Desktop.
QuickSort & ForkJoin
/*
* Copyright 2016 ADVA Optical Networking SE. All rights reserved.
*
* Owner: erohana
*
* $Id: $
*/
package multithread;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.ForkJoinPool;
public class ForkJoinExample {
private static final int SIZE = 10000;
public static void main(String[] args) {
int[] data1 = new int[SIZE];
Random rand = new Random();
for (int i = 0; i < data1.length; i++) {
int randomNum = rand.nextInt((SIZE) + 1);
data1[i] = randomNum;
}
QuickSortAction quickSort = new QuickSortAction(data1);
ForkJoinPool pool = new ForkJoinPool();
pool.invoke(quickSort);
pool.shutdown();
System.out.println("data = " + Arrays.toString(data1));
}
}
package multithread;
import java.util.concurrent.RecursiveAction;
/**
* Quick Sort based on Hoare partition scheme using {@link java.util.concurrent.ForkJoinPool}
*/
public class QuickSortAction extends RecursiveAction{
private int[] data;
private int left;
private int right;
public QuickSortAction(int[] data) {
this.data = data;
left = 0;
right = data.length - 1;
}
public QuickSortAction(int[] data, int left, int right) {
this.data = data;
this.left = left;
this.right = right;
}
@Override
protected void compute() {
if(left < right){
int pivot = partition(data, left, right);
invokeAll(new QuickSortAction(data,left, pivot),
new QuickSortAction(data, pivot + 1, right));
}
}
private int partition(int[] array, int low, int high) {
int pivot = array[low];
int i = low - 1;
int j = high + 1;
while (true){
do {
i++;
}
while (array[i] < pivot);
do {
j--;
}
while (array[j] > pivot);
if (i >= j)
return j;
swap(array, i, j);
}
}
private void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment