daily pastebin goal
25%
SHARE
TWEET

Untitled

a guest May 25th, 2018 68 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. static void printAry(int* ary, int aryNum);
  5. static void sort(int ary[], int left, int right);
  6.  
  7.  
  8. int main (int argc, char *argv[]) {
  9.   int ary[] = {8,4,3,7,6,5,2,1};
  10.   const int aryNum = sizeof(ary) / sizeof(ary[0]);
  11.  
  12.   sort(ary, 0, aryNum - 1);
  13.   printAry(ary, aryNum);
  14.  
  15.   return 0;
  16. }
  17.  
  18. void sort(int ary[], int left, int right) {
  19.   int i, j, k;
  20.   if (left >= right) { return; }
  21.  
  22.   const int mid = (left + right) / 2;
  23.  
  24.   // recursion for split array
  25.   sort(ary, left, mid);
  26.   sort(ary, mid+1, right);
  27.  
  28.   // copy array to temp
  29.   int* temp = (int *)malloc(sizeof(int) * (left+right));
  30.   if (temp == NULL) { exit(0); }
  31.  
  32.   for (i = left; i <= mid ; i++) {
  33.     temp[i] = ary[i];
  34.   }
  35.  
  36.   // reverse
  37.   for (i = mid+1, j = right; i <= right; i++, j--) {
  38.     temp[i] = ary[j];
  39.   }
  40.  
  41.   // merge sort
  42.   i = left;
  43.   j = right;
  44.   for (k = left; k <= right; k++) {
  45.     if (temp[i] <= temp[j]) {
  46.       ary[k] = temp[i++];
  47.     } else {
  48.       ary[k] = temp[j--];
  49.     }
  50.   }
  51.   return;
  52. }
  53.  
  54. void printAry(int* ary, int aryNum) {
  55.   int i;
  56.  
  57.   for (i = 0; i < aryNum; i++) {
  58.     printf("%d ", ary[i]);
  59.   }
  60.   printf("\n");
  61. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top