Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #define NMAX 10001
- void readArr(int n, int arr[NMAX]) {
- for (int i = 0; i < n; i++) {
- scanf("%d", &arr[i]);
- }
- }
- void printArr(int n, const int arr[NMAX]) {
- for (int i = 0; i < n; i++) {
- printf("%d ", arr[i]);
- }
- putchar('\n');
- }
- void merge(int arr[NMAX], int le, int mid, int ri) {
- int n1 = mid - le + 1;
- int n2 = ri - mid;
- int leArr[n1], riArr[n2 + 1];
- for (int i = 0; i < n1; i++) {
- leArr[i] = arr[le + i];
- }
- for (int i = 0; i < n2; i++) {
- riArr[i] = arr[mid + 1 + i];
- }
- int i = 0, j = 0, k = le;
- while (i < n1 && j < n2) {
- if (leArr[i] <= riArr[j]) {
- arr[k++] = leArr[i++];
- } else {
- arr[k++] = riArr[j++];
- }
- }
- while (i < n1) {
- arr[k++] = leArr[i++];
- }
- while (j < n2) {
- arr[k++] = riArr[j++];
- }
- }
- void mergeSort(int arr[NMAX], int le, int ri) {
- if (le < ri) {
- int mid = le + (ri - le) / 2;
- mergeSort(arr, le, mid);
- mergeSort(arr, mid + 1, ri);
- merge(arr, le, mid, ri);
- }
- }
- int main() {
- int n;
- scanf("%d", &n);
- static int arr[NMAX];
- readArr(n, arr);
- mergeSort(arr, 0, n - 1);
- printArr(n, arr);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement