-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge_sort.java
More file actions
42 lines (32 loc) · 1.05 KB
/
merge_sort.java
File metadata and controls
42 lines (32 loc) · 1.05 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
//Write a program to understand merge sort.
public class SimpleMergeSort {
public static void main(String[] args) {
int[] arr = {6, 3, 9, 5, 2};
mergeSort(arr, 0, arr.length - 1);
for (int num : arr)
System.out.print(num + " ");
}
static void mergeSort(int[] arr, int start, int end) {
if (start >= end) return;
int mid = (start + end) / 2;
mergeSort(arr, start, mid);
mergeSort(arr, mid + 1, end);
merge(arr, start, mid, end);
}
static void merge(int[] arr, int start, int mid, int end) {
int[] temp = new int[end - start + 1];
int i = start, j = mid + 1, k = 0;
while (i <= mid && j <= end) {
if (arr[i] < arr[j])
temp[k++] = arr[i++];
else
temp[k++] = arr[j++];
}
while (i <= mid)
temp[k++] = arr[i++];
while (j <= end)
temp[k++] = arr[j++];
for (int x = 0; x < temp.length; x++)
arr[start + x] = temp[x];
}
}