Created
June 1, 2016 12:40
-
-
Save EliaRohana/25b924048d990c5358313d18daf8f491 to your computer and use it in GitHub Desktop.
QuickSort & ForkJoin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * 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)); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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