File: MSort.java

package info (click to toggle)
concurrent-dfsg 1.3.4-6
  • links: PTS
  • area: main
  • in suites: bookworm
  • size: 976 kB
  • sloc: java: 10,704; xml: 49; makefile: 12
file content (310 lines) | stat: -rw-r--r-- 8,130 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
import EDU.oswego.cs.dl.util.concurrent.*;
import java.util.Random;

/**
 * Sample sort program adapted from a demo in
 * <A href="http://supertech.lcs.mit.edu/cilk/"> Cilk</A> and
 * <A href="http://www.cs.utexas.edu/users/hood/"> Hood</A>.
 * 
 **/

class MSort {

  public static void main (String[] args) {
    try {
      int n = 262144;
      int p = 2;
  
      try {
        p = Integer.parseInt(args[0]);
        n = Integer.parseInt(args[1]);
      }

      catch (Exception e) {
        System.out.println("Usage: java MSort <threads> <array size>");
        return;
      }

      int[] A = new int[n];

      // Fill in array A with random values.
      Random rng = new Random();
      for (int i = 0; i < n; i++) A[i] = rng.nextInt();

      int[] workSpace = new int[n];

      FJTaskRunnerGroup g = new FJTaskRunnerGroup(p);
      Sorter t = new Sorter(A, 0, workSpace, 0, n);
      g.invoke(t);
      g.stats();

      //      checkSorted(A, n);

    }
    catch (InterruptedException ex) {}
  }

  static void checkSorted (int[] A, int n)  {
    for (int i = 0; i < n - 1; i++) {
      if (A[i] > A[i+1]) {
        throw new Error("Unsorted at " + i + ": " + A[i] + " / " + A[i+1]);
      }
    }
  }

  /* Threshold values */

  // Cutoff for when to do sequential versus parallel merges 
  static final int MERGE_SIZE = 2048;

  // Cutoff for when to do sequential quicksort versus parallel mergesort
  static final int QUICK_SIZE = 2048;

  // Cutoff for when to use insertion-sort instead of quicksort
  static final int INSERTION_SIZE = 20;



  static class Sorter extends FJTask {
    final int[] A;          // Input array.
    final int aLo;          // offset into the part of array we deal with
    final int[] W;          // workspace for merge
    final int wLo;
    final int n;            // Number of elements in (sub)arrays.


    Sorter (int[] A, int aLo, int[] W, int wLo, int n) {
      this.A = A;
      this.aLo = aLo;
      this.W = W;
      this.wLo = wLo;
      this.n = n;
    }

    public void run()  {

      /*
        Algorithm:
        
        IF array size is small, just use a sequential quicksort
        
        Otherwise:
          Break array in half.
          For each half,
             break the half in half (i.e., quarters),
                 sort the quarters
                 merge them together
          Finally, merge together the two halves.
      */

      if (n <= QUICK_SIZE) {
        qs();
      }
      else {

        int q = n/4;
        
        coInvoke(new Seq(new Par(new Sorter(A, aLo, 
                                            W, wLo, 
                                            q),
                                 
                                 new Sorter(A, aLo+q, 
                                            W, wLo+q, 
                                            q)
                                 ),
                         
                         new Merger(A, aLo,   q, 
                                    A, aLo+q, q,
                                    W, wLo)
                         ),

                 new Seq(new Par(new Sorter(A, aLo+q*2, 
                                            W, wLo+q*2, 
                                            q),
                                 
                                 new Sorter(A, aLo+q*3,
                                            W, wLo+q*3,
                                            n-q*3)
                                 ),
                         
                         new Merger(A, aLo+q*2, q, 
                                    A, aLo+q*3, n-q*3,
                                    W, wLo+q*2)
                         )
                 );

        invoke(new Merger(W, wLo,     q*2, 
                          W, wLo+q*2, n-q*2,
                          A, aLo));

      }
    }


    /** Relay to quicksort within sync method to ensure memory barriers **/
    synchronized void qs() {
      quickSort(aLo, aLo+n-1);
    }
      
    /** A standard sequential quicksort **/
    void quickSort(int lo, int hi) {

      // If under threshold, use insertion sort
      if (hi-lo+1l <= INSERTION_SIZE) {
        for (int i = lo + 1; i <= hi; i++) {
          int t = A[i];
          int j = i - 1;
          while (j >= lo && A[j] > t) {
            A[j+1] = A[j];
            --j;
          }
          A[j+1] = t;
        }
        return;
      }


      //  Use median-of-three(lo, mid, hi) to pick a partition. 
      //  Also swap them into relative order while we are at it.
      
      int mid = (lo + hi) / 2;
      
      if (A[lo] > A[mid]) {
        int t = A[lo]; A[lo] = A[mid]; A[mid] = t;
      }
      if (A[mid]> A[hi]) {
        int t = A[mid]; A[mid] = A[hi]; A[hi] = t;

        if (A[lo]> A[mid]) {
          t = A[lo]; A[lo] = A[mid]; A[mid] = t;
        }

      }
      
      int left = lo+1;           // start one past lo since already handled lo
      int right = hi-1;          // similarly
      
      int partition = A[mid];
      
      for (;;) {
        
        while (A[right] > partition) 
          --right;
        
        while (left < right && A[left] <= partition) 
          ++left;
        
        if (left < right) {
          int t = A[left]; A[left] = A[right]; A[right] = t;
          --right;
        }
        else break;
        
      }
      
      quickSort(lo,    left);
      quickSort(left+1, hi);
      
    }

  }


  static class Merger extends FJTask {

    final int[] A;           // First sorted array.
    final int aLo;           // first index of A
    final int aSize;         // number of elements

    final int[] B;           // Second sorted array.
    final int bLo;
    final int bSize;         

    final int[] out;         // Output array.
    final int outLo;

    Merger (int[] A,   int aLo, int aSize,
            int[] B,   int bLo, int bSize,
            int[] out, int outLo) {

      this.out = out;
      this.outLo = outLo;

      // A must be largest of the two for split. Might as well swap now.
      if (aSize >= bSize) {
        this.A = A;    this.aLo = aLo;    this.aSize = aSize;
        this.B = B;    this.bLo = bLo;    this.bSize = bSize;
      }
      else {
        this.A = B;    this.aLo = bLo;    this.aSize = bSize;
        this.B = A;    this.bLo = aLo;    this.bSize = aSize;
      }
    }

    public void run() {

      /*
        Algorithm:
        If the arrays are small, then just sequentially merge.
        
        Otherwise:
          Split A in half.
          Find the greatest point in B less than the beginning
             of the second half of A.
          In parallel:
               merge the left half of A with elements of B up to split point
               merge the right half of A with elements of B past split point
      */

      if (aSize <= MERGE_SIZE) {
        merge();
      }
      else {

        int aHalf = aSize / 2;
        int bSplit = findSplit(A[aLo + aHalf]);
        
        coInvoke(new Merger(A,   aLo, aHalf, 
                            B,   bLo, bSplit, 
                            out, outLo), 
                 new Merger(A,   aLo+aHalf, aSize-aHalf,
                            B,   bLo+bSplit, bSize-bSplit,
                            out, outLo+aHalf+bSplit));
      }
    }

    /** find greatest point in B less than value. return 0-based offset **/
    synchronized int findSplit(int value) {
      int low = 0;
      int high = bSize;
      while (low < high) {
        int middle = low + (high - low) / 2;
        if (value <= B[bLo+middle])
          high = middle;
        else
          low = middle + 1;
      }
      return high;
    }

    /** A standard sequential merge **/
    synchronized void merge() {
      int a = aLo;
      int aFence = aLo+aSize;
      int b = bLo;
      int bFence = bLo+bSize;
      int k = outLo;

      while (a < aFence && b < bFence) {
        if (A[a] < B[b]) 
          out[k++] = A[a++];
        else 
          out[k++] = B[b++];
      }

      while (a < aFence) out[k++] = A[a++];
      while (b < bFence) out[k++] = B[b++];
    }
  }

}