-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergeSort.java
More file actions
52 lines (43 loc) · 1.5 KB
/
mergeSort.java
File metadata and controls
52 lines (43 loc) · 1.5 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
import java.util.Arrays;
public class mergeSort {
int[] data = { 9, -7, -3, 0, 1, 1, 2, 3, 4, 4, 5, 5, 7, 7, 8, 8, 9 };
static void sort(int[] arr) {
if (arr.length < 2) return;
int mid = arr.length / 2;
int[] left_half = new int[mid];
int[] right_half = new int[arr.length - mid];
// copying the elements of array into left_half
for (int i = 0; i < mid; i++) {
left_half[i] = arr[i];
}
// copying the elements of array into right_half
for (int i = mid; i < arr.length; i++) {
right_half[i - mid] = arr[i];
}
sort(left_half);
sort(right_half);
merge(arr, left_half, right_half);
}
static void merge(int[] arr, int[] left_half, int[] right_half) {
int i = 0, j = 0, k = 0;
while (i < left_half.length && j < right_half.length) {
if (left_half[i] < right_half[j]) {
arr[k++] = left_half[i++];
}
else {
arr[k++] = right_half[j++];
}
}
while (i < left_half.length) {
arr[k++] = left_half[i++];
}
while (j < right_half.length) {
arr[k++] = right_half[j++];
}
}
public void mergeSortMethod(){
sort(data);
System.out.println(" The sorted Array in Ascending Order using The Merge sorting approach: ");
System.out.println(Arrays.toString(data));
}
}