ulvis.paste.net

Paste Search Dynamic
Recent pastes
before/after
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. #define MAX 50
  6. #define SENTINEL 777
  7.  
  8. #define NUM 100
  9.  
  10. unsigned short A[NUM];
  11. int L[NUM/2+2], R[NUM/2+2];
  12.  
  13. void merge(unsigned short A[], int left, int mid, int right) {
  14.   int i, j, k;
  15.   int n1 = mid   - left;
  16.   int n2 = right - mid;
  17.   for(i=0;i<n1;i++) L[i] = A[left + i];
  18.   for(i=0;i<n2;i++) R[i] = A[mid  + i];
  19.   L[n1] = R[n2] = SENTINEL;
  20.   i = j = 0;
  21.   for(k=left; k<right; k++)
  22.     if(L[i] <= R[j]) A[k] = L[i++];
  23.     else             A[k] = R[j++];
  24. }
  25.  
  26. void mergeSort(unsigned short A[], int left, int right) {
  27.   int mid;
  28.   if(left+1 < right) {
  29.     mid = (left+right) / 2;
  30.     mergeSort(A,left,mid);
  31.     mergeSort(A,mid,right);
  32.     merge(A,left,mid,right);
  33.   }
  34. }
  35.  
  36. void printData(unsigned short A[]) {
  37.   int i;
  38.   for(i=0;i<NUM;i++) printf("%d ", A[i]);
  39.   printf("\n");
  40. }
  41.  
  42. int main() {
  43.   int i;
  44.  
  45.   srand((unsigned)time(null));
  46.   for(i=0;i<NUM;i++) A[i] = rand() % MAX;
  47.   puts("Before:");
  48.   printData(A);
  49.   mergeSort(A,0,NUM);
  50.   puts("\nAfter:");
  51.   printData(A);
  52.  
  53.   return 0;
  54. }
  55.  
Parsed in 0.007 seconds