Skip to content

Commit 0c68f43

Browse files
authored
Update sort.java
1 parent 8f11c4e commit 0c68f43

1 file changed

Lines changed: 20 additions & 18 deletions

File tree

Basic Codes/sort.java

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,40 +8,42 @@ class Main
88
{
99
void merge(int a[], int l, int m, int r) // merging the splited sorted arrays
1010
{
11-
int n1 = m - l + 1, n2 = r - m;
11+
//merging two arrays i.e L and R
12+
int n1 = m - l + 1; // size of the first array
13+
int n2 = r - m; // size of the second array
1214

13-
int L[] = new int[n1];
14-
int R[] = new int[n2];
15+
int L[] = new int[n1]; // first array
16+
int R[] = new int[n2]; // second array
1517

1618
for (int i = 0; i < n1; ++i)
17-
L[i] = a[l + i];
19+
L[i] = a[l + i]; // assigning values to the first array
1820
for (int j = 0; j < n2; ++j)
19-
R[j] = a[m + 1 + j];
21+
R[j] = a[m + 1 + j]; // assigning values to the second array
2022

21-
int i = 0, j = 0;
22-
int k = l;
23-
while (i < n1 && j < n2) {
23+
int i = 0, j = 0; // pointers t array L and R respectively
24+
int k = l; // pointer to the main array
25+
while (i < n1 && j < n2) { // merging until i and j not reach end of the array
2426
if (L[i] <= R[j]) {
25-
a[k++] = L[i++];
27+
a[k++] = L[i++];
2628
}
2729
else {
2830
a[k++] = R[j++];
2931
}
3032
}
31-
while (i < n1) {
33+
while (i < n1) { // merging 1st array when 2nd array is completely merged
3234
a[k++] = L[i++];
3335
}
34-
while (j < n2) {
36+
while (j < n2) { // merging 2nd array when 1st array is completely merged
3537
a[k++] = R[j++];
3638
}
3739
}
3840
void sort(int arr[], int l, int r) // dividing the array then merging sorted arrays
3941
{
4042
if (l < r) {
41-
int m =l+ (r-l)/2;
42-
sort(arr, l, m);
43-
sort(arr, m + 1, r);
44-
merge(arr, l, m, r);
43+
int m =l+ (r-l)/2; // calculating the mid of the array
44+
sort(arr, l, m); // sorting the left part
45+
sort(arr, m + 1, r); // sorting the right part
46+
merge(arr, l, m, r); // merging the left and right part
4547
}
4648
}
4749
public static void main(String args[])
@@ -51,15 +53,15 @@ public static void main(String args[])
5153
System.out.print("Enter ten numbers for the array");
5254
for(int i=0; i<10; i++)
5355
{
54-
arr[i]=sc.nextInt();
56+
arr[i]=sc.nextInt(); // taking input
5557
}
5658
Main ob = new Main();
57-
ob.sort(arr, 0, arr.length - 1);
59+
ob.sort(arr, 0, arr.length - 1); // sorting
5860

5961
System.out.println("\nSorted array");
6062
int n = arr.length;
6163
for (int i = 0; i < n; ++i)
62-
System.out.print(arr[i] + " ");
64+
System.out.print(arr[i] + " "); // printing the sorted array
6365
System.out.println();
6466
}
6567
}

0 commit comments

Comments
 (0)