-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmergeSort.java
More file actions
46 lines (37 loc) · 989 Bytes
/
mergeSort.java
File metadata and controls
46 lines (37 loc) · 989 Bytes
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
public class mergeSort {
public static void sort(Object[] a)
{
Object aux[] = (Object [])a.clone();
mergesort(aux, a, 0, a.length);
}
private static void mergesort(Object src[], Object dest[], int low, int high)
{
int length = high - low;
if(length < 7)
{
for(int i = low; i<high; i++)
for(int j=i; j> low && ((Comparable)dest[j-1]).compareTo(dest[j]) > 0; j--)
swap(dest, j, j-1);
return;
}
int mid = (low + high) >> 1;
mergesort(dest, src, low, mid);
mergesort(dest, src, mid, high);
if(((Comparable)src[mid-1]).compareTo(src [mid]) <= 0)
{
System.arraycopy(src, low, dest, low, length);
return;
}
for(int i=low, p=low, q=mid; i<high; i++)
if( (q>=high) || (p<mid && ((Comparable)src[p]).compareTo(src[q]) <= 0))
dest[i] = src[p++];
else
dest[i] = src[q++];
}
public static void swap (Object [] x, int a, int b)
{
Object t = x[a];
x[a] = x[b];
x[b] = t;
} // method swap
}