-
Notifications
You must be signed in to change notification settings - Fork 22
/
sortingTwoSortedLists
74 lines (70 loc) · 1.79 KB
/
sortingTwoSortedLists
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
Question: Sort two sorted lists in ascending order
Source: http://www.careercup.com/question?id=5674416807608320
*/
package sortingTwoSortedLists;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;
public class UsingMergeOfMergeSort {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
try{
System.out.println("Enter the size of the first list");
int m = in.nextInt();
System.out.println("Enter elements of the first list");
LinkedList<Integer> l1=new LinkedList<Integer>();
for(int i=0;i<m;i++)
l1.add(in.nextInt());
System.out.println("Enter the size of the second list");
int n = in.nextInt();
System.out.println("Enter elements of the second list");
LinkedList<Integer> l2=new LinkedList<Integer>();
for(int i=0;i<n;i++)
l2.add(in.nextInt());
LinkedList<Integer> result = sortSortedLists(l1,l2);
System.out.println("Result of sorting the two list is: "+print(result));
}
finally{
in.close();
}
}
private static String print(LinkedList<Integer> result) {
StringBuilder sb = new StringBuilder();
Iterator<Integer> iter = result.iterator();
while(iter.hasNext()){
sb.append(iter.next()+" ");
}
return sb.toString();
}
private static LinkedList<Integer> sortSortedLists(LinkedList<Integer> l1,
LinkedList<Integer> l2) {
LinkedList<Integer> result = new LinkedList<Integer>();
int i=0; // This will iterate through first list
int j=0; // This will iterate through second list
while((i<l1.size())&&(j<l2.size())){
if(l1.get(i)<l2.get(j)){
result.add(l1.get(i));
i++;
}
else{
result.add(l2.get(j));
j++;
}
}
while(i<l1.size()){
result.add(l1.get(i));
i++;
}
while(j<l2.size()){
result.add(l2.get(j));
j++;
}
return result;
}
}
/*
Analysis:
Time Complexity = O(m+n)
Space Complexity = O(m+n)
*/