C++mergesort array
时间: 2023-09-01 22:10:36 浏览: 95
Here is an implementation of mergesort algorithm in C to sort an array:
```c
#include <stdio.h>
void merge(int arr[], int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;
int L[n1], R[n2];
for(i = 0; i < n1; i++)
L[i] = arr[left + i];
for(j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
i = 0;
j = 0;
k = left;
while(i < n1 && j < n2) {
if(L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
while(i < n1) {
arr[k] = L[i];
i++;
k++;
}
while(j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergesort(int arr[], int left, int right) {
if(left < right) {
int mid = left + (right - left) / 2;
mergesort(arr, left, mid);
mergesort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
void printArray(int arr[], int size) {
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[] = { 12, 11, 13, 5, 6, 7 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
printf("Given array is \n");
printArray(arr, arr_size);
mergesort(arr, 0, arr_size - 1);
printf("\nSorted array is \n");
printArray(arr, arr_size);
return 0;
}
```
The `merge` function takes the left, middle, and right indices of the array as input and merges the two subarrays left to mid and mid+1 to right into a single sorted array. The `mergesort` function recursively divides the input array into two halves, sorts them, and then merges them using the `merge` function.
The `printArray` function is used to print the elements of an array.
In the main function, we define an array of integers, print the array before sorting, call the mergesort function to sort the array, and print the sorted array.
阅读全文