| 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 |
package dr.util; |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 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 |
} |