Neocortex 🧠

Search

Search IconIcon to open search

Merging in Merge Sort

Last updated Dec 21, 2021 Edit Source

After the recursive calls return two sorted lists, you need to merge them. Since they are both sorted, merging them into a new sorted list can be done in $O(n)$ complexity. Here is a subsequent java code that would achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public static int[] merge(int[] l1, int[] l2){
	int[] merged = new int[l1.length + l2.length];
	int i = 0;
	int j = 0;
	while(i + j < merged.length){
		if(i < l1.length && (l2.length <= j || l1[i] > l2[j]))
			merged[i+j] = l1[i++];
		else
			merged[i+j] = l2[j++];
	}
	return merged;
}

Interactive Graph