Advertisement
STANAANDREY

mergesort

Jul 22nd, 2023
1,313
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.33 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define NMAX 10001
  4.  
  5. void readArr(int n, int arr[NMAX]) {
  6.     for (int i = 0; i < n; i++) {
  7.         scanf("%d", &arr[i]);
  8.     }
  9. }
  10.  
  11. void printArr(int n, const int arr[NMAX]) {
  12.     for (int i = 0; i < n; i++) {
  13.         printf("%d ", arr[i]);
  14.     }
  15.     putchar('\n');
  16. }
  17.  
  18. void merge(int arr[NMAX], int le, int mid, int ri) {
  19.     int n1 = mid - le + 1;
  20.     int n2 = ri - mid;
  21.     int leArr[n1], riArr[n2 + 1];
  22.  
  23.     for (int i = 0; i < n1; i++) {
  24.         leArr[i] = arr[le + i];
  25.     }
  26.     for (int i = 0; i < n2; i++) {
  27.         riArr[i] = arr[mid + 1 + i];
  28.     }
  29.  
  30.     int i = 0, j = 0, k = le;
  31.     while (i < n1 && j < n2) {
  32.         if (leArr[i] <= riArr[j]) {
  33.             arr[k++] = leArr[i++];
  34.         } else {
  35.             arr[k++] = riArr[j++];
  36.         }
  37.     }
  38.     while (i < n1) {
  39.         arr[k++] = leArr[i++];
  40.     }
  41.     while (j < n2) {
  42.         arr[k++] = riArr[j++];
  43.     }
  44. }
  45.  
  46. void mergeSort(int arr[NMAX], int le, int ri) {
  47.     if (le < ri) {
  48.         int mid = le + (ri - le) / 2;
  49.         mergeSort(arr, le, mid);
  50.         mergeSort(arr, mid + 1, ri);
  51.         merge(arr, le, mid, ri);
  52.     }
  53. }
  54.  
  55. int main() {
  56.     int n;
  57.     scanf("%d", &n);
  58.     static int arr[NMAX];
  59.     readArr(n, arr);
  60.  
  61.     mergeSort(arr, 0, n - 1);
  62.  
  63.     printArr(n, arr);
  64.     return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement