C++mergesort aaray
时间: 2023-08-29 15:12:40 浏览: 73
Here's an example implementation of merge sort in C:
```
#include <stdio.h>
void merge(int arr[], int left[], int right[], int leftSize, int rightSize) {
int i = 0, j = 0, k = 0;
while (i < leftSize && j < rightSize) {
if (left[i] <= right[j]) {
arr[k] = left[i];
i++;
} else {
arr[k] = right[j];
j++;
}
k++;
}
while (i < leftSize) {
arr[k] = left[i];
i++;
k++;
}
while (j < rightSize) {
arr[k] = right[j];
j++;
k++;
}
}
void mergeSort(int arr[], int size) {
if (size < 2) {
return;
}
int mid = size / 2;
int left[mid];
int right[size - mid];
for (int i = 0; i < mid; i++) {
left[i] = arr[i];
}
for (int i = mid; i < size; i++) {
right[i - mid] = arr[i];
}
mergeSort(left, mid);
mergeSort(right, size - mid);
merge(arr, left, right, mid, size - mid);
}
int main() {
int arr[] = { 5, 2, 9, 1, 5, 6 };
int size = sizeof(arr) / sizeof(arr[0]);
printf("Unsorted array: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
mergeSort(arr, size);
printf("Sorted array: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
In this implementation, `merge` takes two sorted subarrays, `left` and `right`, and merges them into a single sorted array `arr`. `mergeSort` recursively splits the input array into smaller subarrays, sorts each subarray with `mergeSort`, and then merges the sorted subarrays with `merge`. The `main` function demonstrates the usage of `mergeSort` on an example array.
阅读全文