-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge_Sort_Optimized.java
More file actions
73 lines (56 loc) · 1.98 KB
/
Merge_Sort_Optimized.java
File metadata and controls
73 lines (56 loc) · 1.98 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
71
72
73
package datastructures;
public class Merge_Sort_Optimized {
// Function to perform Merge Sort
public static void mergeSort(int[] arr) {
if (arr.length < 2) {
return; // Array is already sorted
}
int mid = arr.length / 2;
// Create left and right subarrays
int[] left = new int[mid];
int[] right = new int[arr.length - mid];
// Copy data to left and right subarrays
System.arraycopy(arr, 0, left, 0, mid);
System.arraycopy(arr, mid, right, 0, arr.length - mid);
// Recursively sort the subarrays
mergeSort(left);
mergeSort(right);
// Merge the sorted subarrays
merge(arr, left, right);
}
// Function to merge two sorted subarrays
private static void merge(int[] arr, int[] left, int[] right) {
int i = 0, j = 0, k = 0;
// Merge the left and right arrays into arr
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
arr[k++] = left[i++];
} else {
arr[k++] = right[j++];
}
}
// Copy the remaining elements of left, if any
while (i < left.length) {
arr[k++] = left[i++];
}
// Copy the remaining elements of right, if any
while (j < right.length) {
arr[k++] = right[j++];
}
}
// Function to print the array
public static void printArray(int[] arr) {
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] arr = {38, 27, 43, 3, 9, 82, 10};
System.out.println("Original array:");
printArray(arr);
mergeSort(arr);
System.out.println("Sorted array:");
printArray(arr);
}
}