Advertisement
Guest User

Untitled

a guest
Nov 21st, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. import java.util.List;
  4. import java.util.concurrent.RecursiveTask;
  5.  
  6. class DivideTask extends RecursiveTask<int[]> {
  7.  
  8. int[] arrayToDivide;
  9.  
  10. public DivideTask(int[] arrayToDivide) {
  11. this.arrayToDivide = arrayToDivide;
  12. }
  13.  
  14. private List<int[]> partitionArray(){
  15.  
  16. int [] partition1 = Arrays.copyOfRange(arrayToDivide, 0,
  17. arrayToDivide.length / 2);
  18.  
  19. int [] partition2 = Arrays.copyOfRange(arrayToDivide,
  20. arrayToDivide.length / 2,
  21. arrayToDivide.length);
  22. return Arrays.asList(partition1,partition2);
  23.  
  24. }
  25.  
  26. @Override
  27. protected int[] compute() {
  28. List<RecursiveTask> forkedTasks = new ArrayList<>();
  29.  
  30. /*
  31. * We divide the array till it has only 1 element.
  32. * We can also custom define this value to say some
  33. * 5 elements. In which case the return would be
  34. * Arrays.sort(arrayToDivide) instead.
  35. */
  36. if (arrayToDivide.length > 1) {
  37.  
  38. List<int[]> partitionedArray = partitionArray();
  39.  
  40. DivideTask task1 = new DivideTask(partitionedArray.get(0));
  41. DivideTask task2 = new DivideTask(partitionedArray.get(1));
  42. invokeAll(task1, task2);
  43.  
  44. //Wait for results from both the tasks
  45. int[] array1 = task1.join();
  46. int[] array2 = task2.join();
  47.  
  48. //Initialize a merged array
  49. int[] mergedArray =
  50. new int[array1.length + array2.length];
  51.  
  52. scal_tab(task1.join(), task2.join(), mergedArray);
  53.  
  54. return mergedArray;
  55. }
  56. return arrayToDivide;
  57. }
  58.  
  59.  
  60. private void scal_tab(
  61. int[] tab1,
  62. int[] tab2,
  63. int[] scal_tab) {
  64.  
  65. int i = 0, j = 0, k = 0;
  66.  
  67. while ((i < tab1.length) && (j < tab2.length)) {
  68.  
  69. if (tab1[i] < tab2[j]) {
  70. scal_tab[k] = tab1[i++];
  71. } else {
  72. scal_tab[k] = tab2[j++];
  73. }
  74.  
  75. k++;
  76. }
  77.  
  78. if (i == tab1.length) {
  79.  
  80. for (int a = j; a < tab2.length; a++) {
  81. scal_tab[k++] = tab2[a];
  82. }
  83.  
  84. } else {
  85.  
  86. for (int a = i; a < tab1.length; a++) {
  87. scal_tab[k++] = tab1[a];
  88. }
  89.  
  90. }
  91. }
  92.  
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement