-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsortArray
More file actions
66 lines (59 loc) · 1.27 KB
/
sortArray
File metadata and controls
66 lines (59 loc) · 1.27 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
package Udemyprograms;
public class Arrays7GeeksForGeeks {
public static int[] sortArray(int[] arr) {
int L = 0;
int R = arr.length - 1;
sort(arr, L, R);
return arr;
}
public static void sort(int[] arr, int L, int R) {
if (L < R) {
int mid = L + R / 2;
sort(arr, L, mid);
sort(arr, mid + 1, R);
merge(L, mid, R, arr);
}
}
public static void merge(int L, int mid, int R, int[] arr) {
int l = mid - L + 1;
int r = R - mid;
int[] leftArray = new int[l];
int[] rightArray = new int[r];
for (int i = 0; i < l; i++) {
leftArray[i] = arr[L + i];
}
for (int j = 0; j < r; j++) {
rightArray[j] = arr[mid + 1 + j];
}
int i = 0;
int j = 0;
int k = L;
while (i < l && j < r) {
if (leftArray[i] <= rightArray[j]) {
arr[k] = leftArray[i];
i++;
} else {
arr[k] = rightArray[j];
j++;
}
k++;
}
while (i < l) {
arr[k] = leftArray[i];
i++;
k++;
}
while (j < r) {
arr[k] = rightArray[j];
j++;
k++;
}
}
public static void main(String args[]) {
int[] arr = {7, 0, 2};
sortArray(arr);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}