Debian Codegraph @

src/dr/util/MergeSort.java

raw symbols SCIP
1 /*
2 * MergeSort.java
3 *
4 * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
5 *
6 * This file is part of BEAST.
7 * See the NOTICE file distributed with this work for additional
8 * information regarding copyright ownership and licensing.
9 *
10 * BEAST is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * BEAST is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with BEAST; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
24 */
25
26 package dr.util;
27 /**
28 * An implementation of MergeSort, needs to be subclassed to
29 * compare the terms.
30 *
31 * @author Scott Violet
32 */
33 public abstract class MergeSort {
34 protected Object toSort[];
35 protected Object swapSpace[];
36
37 public void sort(Object array[]) {
38 if(array != null && array.length > 1)
39 {
40 int maxLength;
41
42 maxLength = array.length;
43 swapSpace = new Object[maxLength];
44 toSort = array;
45 this.mergeSort(0, maxLength - 1);
46 swapSpace = null;
47 toSort = null;
48 }
49 }
50
51 public abstract int compareElementsAt(int beginLoc, int endLoc);
52
53 protected void mergeSort(int begin, int end) {
54 if(begin != end)
55 {
56 int mid;
57
58 mid = (begin + end) / 2;
59 this.mergeSort(begin, mid);
60 this.mergeSort(mid + 1, end);
61 this.merge(begin, mid, end);
62 }
63 }
64
65 protected void merge(int begin, int middle, int end) {
66 int firstHalf, secondHalf, count;
67
68 firstHalf = count = begin;
69 secondHalf = middle + 1;
70 while((firstHalf <= middle) && (secondHalf <= end))
71 {
72 if(this.compareElementsAt(secondHalf, firstHalf) < 0)
73 swapSpace[count++] = toSort[secondHalf++];
74 else
75 swapSpace[count++] = toSort[firstHalf++];
76 }
77 if(firstHalf <= middle)
78 {
79 while(firstHalf <= middle)
80 swapSpace[count++] = toSort[firstHalf++];
81 }
82 else
83 {
84 while(secondHalf <= end)
85 swapSpace[count++] = toSort[secondHalf++];
86 }
87 for(count = begin;count <= end;count++)
88 toSort[count] = swapSpace[count];
89 }
90 }