Question
Below are two codes, do this code in two C language Need this Code with C language 1. Array with merge sort: #include using namespace
Below are two codes, do this code in two C language
Need this Code with C language
1. Array with merge sort:
#include
void merge(int arr[], int l, int m, int r, int size) { int i = l; int j = m + 1; int k = l; int temp[size];
while (i <= m && j <= r) { if (arr[i] <= arr[j]) { temp[k] = arr[i]; i++; k++; } else { temp[k] = arr[j]; j++; k++; } } while (i <= m) { temp[k] = arr[i]; i++; k++; }
while (j <= r) { temp[k] = arr[j]; j++; k++; } for (int p = l; p <= r; p++) { arr[p] = temp[p]; } }
void mergeSort(int arr[], int l, int r, int size) { if (l < r) { int m = (l + r) / 2; mergeSort(arr, l, m, size); mergeSort(arr, m + 1, r, size); merge(arr, l, m, r, size); } }
int main() { int size; cin >> size; int myarray[size]; for (int i = 0; i < size; i++) { cin >> myarray[i]; }
mergeSort(myarray, 0, (size - 1), size);
for (int i = 0; i < size; i++) { cout << myarray[i] << " "; }
return 0; }
2. Linked list with merge sort:
#include
class Node { public: int data; Node* next; };
Node* SortedMerge(Node* a, Node* b); void FrontBackSplit(Node* source, Node** frontRef, Node** backRef);
void MergeSort(Node** headRef) { Node* head = *headRef; Node* a;
Node* b;
if ((head == NULL) || (head->next == NULL)) { return; }
FrontBackSplit(head, &a, &b);
MergeSort(&a); MergeSort(&b);
*headRef = SortedMerge(a, b); }
Node* SortedMerge(Node* a, Node* b) { Node* result = NULL;
if (a == NULL) return (b); else if (b == NULL) return (a);
if (a->data <= b->data) { result = a;
result->next = SortedMerge(a->next, b); } else { result = b; result->next = SortedMerge(a, b->next); } return (result); }
void FrontBackSplit(Node* source, Node** frontRef, Node** backRef) { Node* fast; Node* slow; slow = source; fast = source->next;
while (fast != NULL) { fast = fast->next; if (fast != NULL) { slow = slow->next; fast = fast->next; } }
*frontRef = source; *backRef = slow->next;
slow->next = NULL; }
void printList(Node* node) { while (node != NULL) { cout << node->data << " "; node = node->next; } }
void push(Node** head_ref, int new_data) {
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node; }
int main() {
Node* res = NULL;
Node* a = NULL;
push(&a, 15); push(&a, 10); push(&a, 5); push(&a, 20); push(&a, 3); push(&a, 2);
MergeSort(&a);
cout << "Sorted Linked List is: "; printList(a);
return 0; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started