merge Lists Algorithm
The merge lists algorithm is a fundamental technique in computer science, primarily used for merging two sorted lists into a single sorted list. It is often employed as a part of more complex sorting algorithms, such as merge sort, where the input list is recursively divided into smaller sorted sublists, and then these sublists are merged to produce the final sorted list. The primary benefit of the merge lists algorithm is its efficiency, as it takes linear time, O(n), to combine two sorted lists of length n.
The merge lists algorithm works by iteratively comparing the elements at the front of the two input lists and selecting the smaller element to be added to the output list. This process is repeated until one of the input lists is exhausted, at which point the remaining elements of the non-empty list are appended to the output list. To maintain the sorted order, the algorithm maintains two pointers, each pointing to the current position in the input lists. The pointers are advanced through the lists as the algorithm processes the elements, ensuring that each element is only considered once. This efficient comparison and merging process results in a time complexity of O(n) for the merge lists algorithm, making it an essential building block for more powerful sorting algorithms.
/**
* Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
* Note:
* You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold
* additional elements from nums2.
* The number of elements initialized in nums1 and nums2 are m and n respectively.
*/
#include <iostream>
#include <vector>
using namespace std;
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i = m-1;
int j = n-1;
int k = m + n - 1;
while ( i >= 0 && j >= 0 ) {
if ( nums1[i] > nums2[j] ) {
nums1[k] = nums1[i];
--i;
} else {
nums1[k] = nums2[j];
--j;
}
--k;
}
while ( j >= 0 ) {
nums1[k] = nums2[j];
--j;
--k;
}
}
void printVec(std::vector<int> & vec ) {
for ( auto x : vec ) {
std::cout << x << " " ;
}
std::cout << std::endl;
}
int main()
{
std::vector<int> vec1 { 2, 4, 6, 8, 10, 0, 0, 0, 0, 0};
std::vector<int> vec2 { 1, 2, 3, 4, 5 };
merge(vec1, 5, vec2, 5 );
printVec(vec1);
return 0;
}