|
| 1 | +#include <iostream> |
| 2 | +using namespace std; |
| 3 | + |
| 4 | +// Merge two sorted subarrays into one sorted array |
| 5 | +void merge(int arr[], int left, int mid, int right) { |
| 6 | + int i, j, k; |
| 7 | + int n1 = mid - left + 1; |
| 8 | + int n2 = right - mid; |
| 9 | + |
| 10 | + // Create temporary arrays |
| 11 | + int L[n1], R[n2]; |
| 12 | + |
| 13 | + // Copy data to temporary arrays |
| 14 | + for (i = 0; i < n1; i++) |
| 15 | + L[i] = arr[left + i]; |
| 16 | + for (j = 0; j < n2; j++) |
| 17 | + R[j] = arr[mid + 1 + j]; |
| 18 | + |
| 19 | + // Merge the temporary arrays back into arr[left..right] |
| 20 | + i = 0; // Initial index of first subarray |
| 21 | + j = 0; // Initial index of second subarray |
| 22 | + k = left; // Initial index of merged subarray |
| 23 | + |
| 24 | + while (i < n1 && j < n2) { |
| 25 | + if (L[i] <= R[j]) { |
| 26 | + arr[k] = L[i]; |
| 27 | + i++; |
| 28 | + } else { |
| 29 | + arr[k] = R[j]; |
| 30 | + j++; |
| 31 | + } |
| 32 | + k++; |
| 33 | + } |
| 34 | + |
| 35 | + // Copy the remaining elements of L[], if there are any |
| 36 | + while (i < n1) { |
| 37 | + arr[k] = L[i]; |
| 38 | + i++; |
| 39 | + k++; |
| 40 | + } |
| 41 | + |
| 42 | + // Copy the remaining elements of R[], if there are any |
| 43 | + while (j < n2) { |
| 44 | + arr[k] = R[j]; |
| 45 | + j++; |
| 46 | + k++; |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +// Merge sort function |
| 51 | +void mergeSort(int arr[], int left, int right) { |
| 52 | + if (left < right) { |
| 53 | + int mid = left + (right - left) / 2; |
| 54 | + |
| 55 | + // Sort first and second halves |
| 56 | + mergeSort(arr, left, mid); |
| 57 | + mergeSort(arr, mid + 1, right); |
| 58 | + |
| 59 | + // Merge the sorted halves |
| 60 | + merge(arr, left, mid, right); |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +// Function to print an array |
| 65 | +void printArray(int arr[], int size) { |
| 66 | + for (int i = 0; i < size; i++) |
| 67 | + cout << arr[i] << " "; |
| 68 | + cout << endl; |
| 69 | +} |
| 70 | + |
| 71 | +// Driver code |
| 72 | +int main() { |
| 73 | + const int size = 10000; |
| 74 | + int arr[size]; |
| 75 | + |
| 76 | + // Generate random numbers for the array |
| 77 | + for (int i = 0; i < size; i++) |
| 78 | + arr[i] = rand() % 10000; |
| 79 | + |
| 80 | + cout << "Original array: "; |
| 81 | + // printArray(arr, size); // Uncomment this line to print the original array |
| 82 | + |
| 83 | + mergeSort(arr, 0, size - 1); |
| 84 | + |
| 85 | + cout << "Sorted array: "; |
| 86 | + // printArray(arr, size); // Uncomment this line to print the sorted array |
| 87 | + |
| 88 | + return 0; |
| 89 | +} |
0 commit comments