702674. Merge and Sort
Merge and Sort
Slug: merge-and-sort5821
Difficulty: Basic
Id: 702674
Topic Tags: Arrays, Sorting, Merge Sort, Data Structures, Algorithms
Company Tags: None
Summary
The problem involves merging two sorted arrays into a single sorted array. This is a classic example of a sorting algorithm problem that can be solved using the merge sort technique.
Detailed Explanation
To solve this problem, we will implement a merge sort algorithm to merge and sort the two given arrays. The basic idea behind merge sort is to divide the input array into smaller subarrays until each subarray contains only one element (which is already sorted), then merge these subarrays in a way that maintains the sorting.
Here's a step-by-step breakdown of the solution:
- Initialize three variables:
left,right, andresultarrays, representing the input left array, right array, and the result merged array, respectively. - Compare the smallest unprocessed element from each array (i.e., the first elements of both arrays). If the left array's element is smaller, add it to the
resultarray, move on to the next element in the left array. If the right array's element is smaller, add it to theresultarray, move on to the next element in the right array. - Repeat step 2 until one of the arrays becomes empty. At this point, all elements from the non-empty array have been added to the result array.
- Combine the remaining elements (if any) from both arrays into the
resultarray.
The time complexity for this solution is O(n log n), where n is the total number of elements in both input arrays. This is because we are essentially performing a divide-and-conquer operation, splitting the arrays into smaller subarrays until they contain only one element each, and then merging these subarrays to produce the final sorted array.
The space complexity for this solution is O(n), where n is the total number of elements in both input arrays. This is because we need to store all elements from both arrays in the result array.
Optimized Solutions
Java
public static int[] mergeSortedArrays(int[] left, int[] right) {
int[] result = new int[left.length + right.length];
int i = 0, j = 0, k = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
result[k++] = left[i++];
} else {
result[k++] = right[j++];
}
}
while (i < left.length) {
result[k++] = left[i++];
}
while (j < right.length) {
result[k++] = right[j++];
}
return result;
}