Skip to content

Commit a6f3b71

Browse files
authored
88. Merge Sorted Array Java (#82)
Added the solution to 'Merge Sorted Array' which is number 88 in LeetCode Contributed by @avash-poudel
1 parent 9adfbdf commit a6f3b71

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

java/088_Merge_Sorted_Array.java

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
//we are being given two int arrays and two int variables that state the number of elements in each array, respectively
3+
public void merge(int[] nums1, int m, int[] nums2, int n) {
4+
//I am using a counter so that I can iterate through the second array inside the for loop
5+
int counter = 0;
6+
//We know that nums1 is of the size n + m, so we can add all the elements to the array and sort them later
7+
//For loop adds all values of nums2 to the end of nums1
8+
for(int i=m; i<nums1.length; i++){
9+
nums1[i] = nums2[counter++];
10+
}
11+
//Now that all of the elements are in the array, we can begin the sort process
12+
//Though we could use the Arrays.sort function to quickly sort the array, I wanted to implement a sorting algorithm myself
13+
//I am implementing what's called a "Bubble Sorting Algorithm" to sort this array
14+
//This should work best in our scenario as we don't have to work with a large list of numbers
15+
for(int i=0; i<nums1.length; i++){
16+
for(int j=0; j<nums1.length-i-1; j++){
17+
if(nums1[j] > nums1[j+1]){
18+
int temp = nums1[j+1];
19+
nums1[j+1] = nums1[j];
20+
nums1[j] = temp;
21+
}
22+
}
23+
}
24+
//The following function simply prints out everything that is contained within our num1 array
25+
for(int i=0; i<nums1.length; i++){
26+
System.out.println(nums1[i]);
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)