Sunday, February 6, 2022

Merge Sort A Linked List




import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Merge_Sort_A_LinkedList {
public static class Node {
int data;
Node next;
}

public static class LinkedList {
Node head;
Node tail;
int size;

void addLast(int val) {
Node temp = new Node();
temp.data = val;
temp.next = null;

if (size == 0) {
head = tail = temp;
} else {
tail.next = temp;
tail = temp;
}

size++;
}

public int size() {
return size;
}

public void display() {
for (Node temp = head; temp != null; temp = temp.next) {
System.out.print(temp.data + " ");
}
System.out.println();
}

public void addFirst(int val) {
Node temp = new Node();
temp.data = val;
temp.next = head;
head = temp;

if (size == 0) {
tail = temp;
}

size++;
}

public static LinkedList mergeTwoSortedLists(LinkedList l1, LinkedList l2) {
LinkedList ml = new LinkedList();

Node one = l1.head;
Node two = l2.head;
while (one != null && two != null) {
if (one.data < two.data) {
ml.addLast(one.data);
one = one.next;
} else {
ml.addLast(two.data);
two = two.next;
}
}

while (one != null) {
ml.addLast(one.data);
one = one.next;
}

while (two != null) {
ml.addLast(two.data);
two = two.next;
}

return ml;
}


// write your code here
public static LinkedList mergeSort(Node head, Node tail) {
// base case
if (head == tail) {
LinkedList base = new LinkedList();
base.addFirst(head.data);
return base;
}
// Step 1
Node mid = getMid(head, tail);

// Step 2: Faith
LinkedList l1 = mergeSort(head, mid);
LinkedList l2 = mergeSort(mid.next, tail);

// Step 3: merge both
LinkedList ll = mergeTwoSortedLists(l1, l2);

return ll;
}

private static Node getMid(Node head, Node tail) {
Node slow = head, fast = head;
while (fast != tail && fast.next != tail) {
slow = slow.next;
fast = fast.next.next;
}

return slow;
}

}

public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int n1 = Integer.parseInt(br.readLine());
LinkedList l1 = new LinkedList();
String[] values1 = br.readLine().split(" ");
for (int i = 0; i < n1; i++) {
int d = Integer.parseInt(values1[i]);
l1.addLast(d);
}

LinkedList sorted = LinkedList.mergeSort(l1.head, l1.tail);
sorted.display();
l1.display();
}
}

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...