-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathMergeSort.java
More file actions
70 lines (64 loc) · 1.88 KB
/
MergeSort.java
File metadata and controls
70 lines (64 loc) · 1.88 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
62
63
64
65
66
67
68
69
70
import java.util.Arrays;
public class MergeSort {
private int [] input;
public MergeSort(int [] input) {
this.input = input;
}
private int [] merge(int left [], int right[]){ // sort items in two arrays in a single array (merge two arrays in a sorted array)
int [] ret = new int [right.length + left.length];
int j = 0;
int right_index = 0;
int left_index = 0;
while (j < ret.length){
if (right_index < right.length && left_index < left.length){
if (right[right_index] < left[left_index]){
ret[j] = right[right_index];
right_index++;
}else {
ret[j] = left[left_index];
left_index++;
}
}else if (right_index < right.length){
ret[j] = right[right_index];
right_index++;
}else {
ret[j] = left[left_index];
left_index++;
}
j++;
}
return ret;
}
public int [] sort(){
if (this.input == null)
return null;
return merge_sort(this.input, this.input.length);
}
private int [] merge_sort(int [] input, int p){
if (input.length == 1){ // return if the array has only one item
return input;
}
return merge( // merge left part and right part
//left part
merge_sort(copyofrange(input, 0, p/2), p/2),
//right part
merge_sort(copyofrange(input, p/2, input.length), input.length - p/2)
);
}
private int [] copyofrange(int [] input, int i, int j){ // copy a range of an array into a new array
int range [] = new int [j-i];
for (int k = i; k < j; k++) {
range [k-i] = input[k];
}
return range;
}
public static void main(String[] args) {
// input array
int array[] = {9,1,0,4,2,-1,5,2, 200, 99, 45, -100};
// merge sort
MergeSort mergesort = new MergeSort(array);
// outputs
System.out.println("Unsorted Array -> "+ Arrays.toString(array));;
System.out.println("MergeSort -> "+ Arrays.toString(mergesort.sort())); // output: MergeSort -> [-100, -1, 0, 1, 2, 2, 4, 5, 9, 45, 99, 200]
}
}