1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| import java.util.Arrays; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveAction;
public class ParallelQuickSort {
private static class QuickSortTask extends RecursiveAction { private final int[] array; private final int left; private final int right;
public QuickSortTask(int[] array, int left, int right) { this.array = array; this.left = left; this.right = right; }
@Override protected void compute() { if (left < right) { int pivotIndex = partition(array, left, right); QuickSortTask leftTask = new QuickSortTask(array, left, pivotIndex - 1); QuickSortTask rightTask = new QuickSortTask(array, pivotIndex + 1, right); invokeAll(leftTask, rightTask); } }
private int partition(int[] array, int left, int right) { int pivot = array[right]; int i = left - 1; for (int j = left; j < right; j++) { if (array[j] <= pivot) { i++; swap(array, i, j); } } swap(array, i + 1, right); return i + 1; }
private void swap(int[] array, int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } }
public static void parallelQuickSort(int[] array) { ForkJoinPool pool = new ForkJoinPool(); pool.invoke(new QuickSortTask(array, 0, array.length - 1)); }
public static void main(String[] args) { int[] array = {9, 5, 3, 7, 2, 8, 6, 1, 4}; System.out.println("Original array: " + Arrays.toString(array) + ", timestamp: " + System.currentTimeMillis()); parallelQuickSort(array); System.out.println("Sorted array: " + Arrays.toString(array) + ", timestamp: " + System.currentTimeMillis()); }
}
|