Skip to content

Commit dd0c80a

Browse files
committed
Solution to sort using merge functionality
1 parent cccad1a commit dd0c80a

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

src/Sorting/SortingProblems.java

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,12 @@ public static void main(String[] args) {
1010
// int [] A = {1, 1, 3, 3};
1111
// int [] A = {0, 1, 2, 0, 1, 2};
1212
// int [] A = {0};
13+
int firstArray [] = {3,7,8,9,10,1,2,3};
14+
int secondArray [] = {2,5,6,11,12};
15+
// int finalArray [] = mergeSortedArrays(firstArray,secondArray);
16+
// System.out.println(Arrays.toString(finalArray));
17+
18+
System.out.println(Arrays.toString(merge(firstArray,0,firstArray.length/2,firstArray.length-1)));
1319
int [] A = {2, 0, 0, 1, 0, 0, 2, 2, 1, 1, 0, 0, 1, 0, 2, 1, 1, 0, 1, 0, 1, 2, 2, 2, 0, 0, 1, 0, 2, 1, 1, 2, 1, 2, 2, 1, 0, 2, 2, 1, 1, 1, 0, 1, 0, 1, 0, 2, 1, 2, 0, 2, 0, 1, 1, 0, 2, 2, 1, 2, 0, 2, 1, 1, 1, 2, 0, 1, 0, 2, 2, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 2, 1, 1, 0, 2, 1, 2, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 1, 1, 0, 2, 1, 2, 2, 2, 1, 2, 2, 0, 1, 0, 1, 2, 1, 1, 0, 1, 2, 0, 1, 0, 2, 2, 1, 2, 1, 0, 2, 2, 1, 1, 0, 2, 1, 2};
1420
int [] answerArray = sortColors(A);
1521
System.out.println(Arrays.toString(answerArray));
@@ -18,6 +24,69 @@ public static void main(String[] args) {
1824
System.out.println(result);
1925
}
2026

27+
static int [] merge(int [] A, int s, int m,int e){
28+
29+
int [] finalArray = new int[e-s+1];
30+
31+
int p1 = s; int p2 = m+1; int p3 = 0;
32+
33+
while (s <= m && p2 <= e){
34+
if (A[p1] < A[p2]){
35+
finalArray[p3] = A[p1];
36+
p1++;
37+
p3++;
38+
}else {
39+
finalArray[p3] = A[p2];
40+
p2++;
41+
p3++;
42+
}
43+
}
44+
while (p1 <= m){
45+
finalArray[p3] = A[p1];
46+
p1++;
47+
p3++;
48+
}
49+
while (p2 <= e){
50+
finalArray[p3] = A[p2];
51+
p2++;
52+
p3++;
53+
}
54+
55+
return finalArray;
56+
}
57+
58+
static int [] mergeSortedArrays(int [] A, int [] B){
59+
60+
int p1 = 0; int p2 = 0; int p3 = 0;
61+
62+
int [] finalArray = new int[A.length+B.length];
63+
64+
while (p1 < A.length && p2 < B.length){
65+
if (A[p1] < B[p2]){
66+
finalArray[p3] = A[p1];
67+
p1++;
68+
p3++;
69+
}else {
70+
finalArray[p3] = B[p2];
71+
p2++;
72+
p3++;
73+
}
74+
}
75+
while (p1 < A.length){
76+
finalArray[p3] = A[p1];
77+
p1++;
78+
p3++;
79+
}
80+
while (p2 < B.length){
81+
finalArray[p3] = B[p2];
82+
p2++;
83+
p3++;
84+
}
85+
86+
return finalArray;
87+
88+
}
89+
2190
static int nobleInteger(int [] A){
2291

2392
HashMap<Integer,Integer> hashMap_1 = new HashMap<>();

0 commit comments

Comments
 (0)