2013-11-26 44 views
2

我有叉/联接计算的示例。有人能否简要介绍一下它在这里的工作原理?叉/联接计算

def quicksortForkJoin(numbers) { 
    withPool { 
     runForkJoin(0, numbers) {index, list -> 
      def groups = list.groupBy {it <=> list[list.size().intdiv(2)]} 
      if ((list.size() < 2) || (groups.size() == 1)) { 
       return [index: index, list: list.clone()] 
      } 
      (-1..1).each { forkOffChild(it, groups[it] ?: [])} 
      return [index: index, list: childrenResults.sort {it.index}.sum {it.list}] 
     }.list 
    } 
} 

回答

3

还好吗?

def quicksortForkJoin(numbers) { 

    // Create a pool of workers the default size 
    withPool { 

     // Run a fork with index 0 and the numbers 
     runForkJoin(0, numbers) {index, list ->   // [1] 

      // Split numbers into 3 groups: 
      // -1: those less than the "middle" number 
      //  0: those equal to the "middle" number 
      //  1: those greater than the "middle" number 
      def groups = list.groupBy {it <=> list[list.size().intdiv(2)]} 

      // If there are less than 2 numbers to sort, or all numbers are equal 
      if ((list.size() < 2) || (groups.size() == 1)) { 

       // return the index and a clone of the current list 
       return [index: index, list: list.clone()] 
      } 

      // Otherwise, fork off a child process for each of the 
      // groups above (less than, equal and greater than) 
      // forkOffChild will not block, and will effectively go back 
      // to line [1] with the new index and list 
      (-1..1).each { forkOffChild(it, groups[it] ?: [])} 

      // Block waiting for all 3 children to finish, then sort the 
      // results so the indexes are [ -1, 0, 1 ] and then join the 
      // lists of numbers back together 
      return [ index: index, 
        list: childrenResults.sort {it.index}.sum {it.list}] 

      // when done, return the `list` property from the final map 
     }.list 
    } 
} 
+0

非常感谢!但我仍然不明白带有“groups”的部分:它是如何分成3组的?这一行'{它<=>列表[list.size()。intdiv(2)]}'是相当混乱。 – user1170330

+1

@ user1170330'list [list.size()。intdiv(2)]'获得“中间”元素,即:[[3,6,4,3,1]]它会给你数字'4' 。所以我们称这个为'mid'。组关闭然后变成'{它0123}'。宇宙飞船操作员基本上在两个元素之间进行“比较”,并返回“-1”,“0”或“1”。因此,'groupBy'接受列表中的每个元素,并返回一个带有3个键的映射(如此评论中的示例列表)[[-1:[3,3,1],0:[4],1 :[6]]' –