-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.java
More file actions
61 lines (51 loc) · 1.67 KB
/
MergeSort.java
File metadata and controls
61 lines (51 loc) · 1.67 KB
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
// AUTHOR: Soel Micheletti
import java.util.Random;
class MergeSort{
public static int[] mergeSort(int[] a) {
return mergeSort(a, new int[a.length], 0, a.length - 1);
}
public static int[] mergeSort(int[] a, int[] tmp, int left, int right) {
if(left < right) {
int mid = (left+right)/2;
mergeSort(a, tmp, left, mid);
mergeSort(a, tmp, mid+1, right);
merge(a, tmp, left, mid, mid+1, right);
}
return a;
}
public static int[] merge(int[] a, int[] tmp, int leftStart, int leftEnd, int rightStart, int rightEnd) {
int size = rightEnd - leftStart + 1;
int index = leftStart;
while(leftStart <= leftEnd && rightStart <= rightEnd) {
if(a[leftStart]<= a[rightStart])
tmp[index++] = a[leftStart++];
else
tmp[index++] = a[rightStart++];
}
while(leftStart<=leftEnd)
tmp[index++] = a[leftStart++];
while(rightStart<=rightEnd)
tmp[index++] = a[rightStart++];
for(int i = 0; i<size; i++) {
a[rightEnd] = tmp[rightEnd];
rightEnd--;
}
return a;
}
public static boolean isSorted(int[] a){
for(int i = 0; i < a.length - 1; i++){
if(a[i] > a[i + 1])
return false;
}
return true;
}
public static void main(String[] args) {
Random ran = new Random();
int[] a = new int[10000];
for(int i = 0; i < a.length; i++){
a[i] = ran.nextInt(10000);
}
mergeSort(a);
System.out.println(isSorted(a));
}
}