समस्या कथन
एक लिंक्ड लिस्ट दी गई है। इसे मर्ज सॉर्ट एल्गोरिदम का उपयोग करके सॉर्ट करें।
List: 10→20→8→17→5→13→4 Sorted list: 4→5→8→10→13→17→20
एल्गोरिदम
1. यदि हेड NULL है या लिस्ट में केवल एक तत्व है तो लिस्ट लौटाएं 2. मूल लिस्ट को 2 भागों में विभाजित करके दो लिस्ट बनाएं 3. लिस्ट के पहले और दूसरे भाग को सॉर्ट करें 4. दोनों सॉर्ट की गई लिस्ट को मर्ज करें
C++ उदाहरण
#include <iostream>
#include <new>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
struct Node {
int data;
struct Node *next;
};
Node* createList(int *arr, int n) {
Node *head, *p;
p = head = new Node;
head->data = arr[0];
head->next = NULL;
for (int i = 1; i < n; ++i) {
p->next = new Node;
p = p->next;
p->data = arr[i];
p->next = NULL;
}
return head;
}
void displayList(Node *head) {
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
Node* mergeSortedLists(Node *head1, Node *head2) {
if (!head1) return head2;
if (!head2) return head1;
Node *result = NULL;
if (head1->data < head2->data) {
result = head1;
result->next = mergeSortedLists(head1->next, head2);
} else {
result = head2;
result->next = mergeSortedLists(head1, head2->next);
}
return result;
}
void splitList(Node *src, Node **fRef, Node **bRef) {
Node *fast = src->next, *slow = src;
while (fast != NULL) {
fast = fast->next;
if (fast != NULL) {
slow = slow->next;
fast = fast->next;
}
}
*fRef = src;
*bRef = slow->next;
slow->next = NULL;
}
void mergeSort(Node **head) {
Node *p = *head, *a = NULL, *b = NULL;
if (!p || !p->next) return;
splitList(p, &a, &b);
mergeSort(&a);
mergeSort(&b);
*head = mergeSortedLists(a, b);
}
int main() {
int arr[] = {10, 20, 8, 17, 5, 13, 4};
Node *head = createList(arr, SIZE(arr));
cout << "Unsorted list: " << endl;
displayList(head);
mergeSort(&head);
cout << "Final sorted list: " << endl;
displayList(head);
return 0;
}
आउटपुट
Unsorted list: 10 20 8 17 5 13 4 Final sorted list: 4 5 8 10 13 17 20