-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeSort.java
95 lines (66 loc) · 1.77 KB
/
MergeSort.java
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package com.iamoperand;
/**
* Created by iamoperand on 28/6/17.
*/
public class MergeSort {
void merge(int arr[], int l, int m, int r){
int n1 = m - l + 1;
int n2 = r - m;
int[] temp1 = new int[n1];
int[] temp2 = new int[n2];
//Fill in the values into the temporary arrays
for(int i=0; i<n1; i++){
temp1[i] = arr[l + i];
//l is not 0 all the time, so keep that in mind!
}
for(int j=0; j<n2; j++){
temp2[j] = arr[m+1+j];
}
//Fill the original array with the sorted values
int i = 0,j = 0, k = l;
//l is not 0 all the time, keep that in mind!
while(i<n1 && j<n2){
if(temp1[i]<=temp2[j]){
arr[k] = temp1[i];
i++;
}
else{
arr[k] = temp2[j];
j++;
}
k++;
}
while(i<n1){
arr[k] = temp1[i];
i++;
k++;
}
while(j<n2){
arr[k] = temp2[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r){
if(l<r){
int m = (l+r)/2;
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
void printArray(int arr[]) {
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String args[]){
MergeSort m = new MergeSort();
int[] arr = {5,1,99,2,81,77};
int r = arr.length - 1;
m.mergeSort(arr, 0, r);
System.out.println("The sorted array is: ");
m.printArray(arr);
}
}