University stuff.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Parallel.java 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import java.util.Random;
  2. import java.util.Arrays;
  3. class Parallel implements A2Solver {
  4. class Worker implements Runnable {
  5. int[] a; // Shared, mutate a[min] to a[max - 1]
  6. int k;
  7. int min; // Inclusive
  8. int max; // Exclusive
  9. Worker(int[] a, int k, int min, int max) {
  10. this.a = a;
  11. this.k = k;
  12. this.min = min;
  13. this.max = max;
  14. }
  15. public void run() {
  16. Util.insertionSortReverse(a, min, min + k);
  17. // Insert the biggest values in a[k..n] into a[0..k-1]
  18. for (int i = min + k; i < max; ++i) {
  19. Util.insertAt(a, min, k, i);
  20. }
  21. }
  22. }
  23. public void solveA2(int[] a, int k) {
  24. // Set up workers and start threads
  25. int nthreads = Runtime.getRuntime().availableProcessors();
  26. Worker[] workers = new Worker[nthreads];
  27. Thread[] threads = new Thread[nthreads];
  28. int prev = 0;
  29. int step = (a.length / nthreads) + 1;
  30. for (int i = 0; i < nthreads; ++i) {
  31. Worker w = new Worker(
  32. a, k, prev, Math.min(prev + step, a.length - 1));
  33. workers[i] = w;
  34. Thread t = new Thread(w);
  35. threads[i] = t;
  36. t.start();
  37. prev += step;
  38. }
  39. // Wait for workers to complete
  40. for (Thread t: threads) {
  41. try {
  42. t.join();
  43. } catch (InterruptedException ex) {}
  44. }
  45. // Merge
  46. for (int wi = 1; wi < nthreads; ++wi) {
  47. Worker w = workers[wi];
  48. for (int i = 0; i < k; ++i) {
  49. if (a[w.min + i] > a[k - 1])
  50. Util.insertAt(a, 0, k, w.min + i);
  51. }
  52. }
  53. }
  54. }