C Online Compiler
Example: Merge Sorted Sub-arrays in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Merge Sorted Sub-arrays #include <stdio.h> #include <stdlib.h> // Required for malloc and free void merge(int arr[], int left, int mid, int right) { int i, j, k; // Calculate sizes of the two sub-arrays int n1 = mid - left + 1; int n2 = right - mid; // Create temporary arrays to hold the elements of the two halves int* L = (int*)malloc(n1 * sizeof(int)); int* R = (int*)malloc(n2 * sizeof(int)); // Copy data from the original array into the temporary arrays for (i = 0; i < n1; i++) L[i] = arr[left + i]; for (j = 0; j < n2; j++) R[j] = arr[mid + 1 + j]; // Merge the temporary arrays back into the original array arr[left..right] i = 0; // Initial index of first sub-array j = 0; // Initial index of second sub-array k = left; // Initial index of merged sub-array in the original array while (i < n1 && j < n2) { if (L[i] <= R[j]) { // Compare elements from both halves arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } // Copy any remaining elements of L[] while (i < n1) { arr[k] = L[i]; i++; k++; } // Copy any remaining elements of R[] while (j < n2) { arr[k] = R[j]; j++; k++; } // Free the dynamically allocated memory to prevent memory leaks free(L); free(R); }
Output
Clear
ADVERTISEMENTS