Skip to content

Instantly share code, notes, and snippets.

@nida-001
Created September 18, 2013 13:47
Show Gist options
  • Save nida-001/6609391 to your computer and use it in GitHub Desktop.
Save nida-001/6609391 to your computer and use it in GitHub Desktop.
並列奇偶転置ソートを試験的に作ってみた
package oddeven;
import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ConcurrentOddEvenSort {
public static void main(String[] args) throws InterruptedException, ExecutionException {
int[] array = new int[]{8, 4, 3, 7, 6, 5, 2, 1, -1, 7, 10, 9};
boolean changed = true;
while (changed) {
changed = false;
ExecutorService executors = Executors.newFixedThreadPool(8);
for (int i = 0; i < array.length-1; i += 2) {
changed |= executors.submit(new Swapper(array, i)).get();
}
executors.shutdown();
executors = Executors.newFixedThreadPool(8);
for (int i = 1; i < array.length-1; i+=2) {
changed |= executors.submit(new Swapper(array, i)).get();
}
executors.shutdown();
}
System.out.println(Arrays.toString(array));
}
private static class Swapper implements Callable<Boolean> {
private final int[] array;
private final int i;
public Swapper(int[] array, int i) {
super();
this.array = array;
this.i = i;
}
@Override
public Boolean call() {
final boolean changed;
if (array[i] > array[i+1]) {
final int temp = array[i+1];
array[i+1] = array[i];
array[i] = temp;
changed = true;
} else {
changed = false;
}
return changed;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment