daily pastebin goal
30%
SHARE
TWEET

Untitled

a guest Aug 10th, 2018 58 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <math.h>
  3. #include <stdlib.h>
  4.  
  5. #define MAX_NUMBER 100
  6. #define LIST_SIZE 10
  7.  
  8. int compareCounter = 0;
  9.  
  10. int compare(int a, int b) {
  11.     compareCounter++;
  12.     return a - b;
  13. }
  14.  
  15. int* generateRandomList(int size) {
  16.     int* list = malloc(sizeof(int)*size);
  17.     int i;
  18.     for (i=0; i<size; i++) {
  19.         list[i] = rand() % MAX_NUMBER;
  20.     }
  21.     return list;
  22. }
  23.  
  24. void printList(int* list,int size) {
  25.     int i;
  26.     for (i=0; i<size; i++) {
  27.         printf("%d ",list[i]);
  28.     }
  29.     printf("\n");
  30. }
  31.  
  32. int* merge(int* list1,int* list2,int size1,int size2){
  33.     int mergedSize = size1 + size2;
  34.     int* mergedList = malloc(sizeof(int)*mergedSize);
  35.     int i1=0,i2=0,i3=0;
  36.     for (i3=0;i3<mergedSize;i3++) {
  37.         // VUL HIER AAN!
  38.         if(list1[i1] > list2[i2])
  39.         {
  40.             //If its bigger then we dont put the list 1 value but we take the list 2 value and we increment list 2
  41.             mergedList[i3] = list2[i2];
  42.             i2++;
  43.         } else if(list1[i1] < list2[i2]) {
  44.             mergedList[i3] = list1[i1];
  45.             i1++;
  46.         } else {
  47.             //Its equal
  48.             mergedList[i3] = list2[i2];
  49.             i2++;
  50.         }
  51.     }
  52.     return mergedList;
  53. }
  54.  
  55. void mergeSort(int *list,int size) {
  56.     if (size<=1) return;
  57.     int* list1 = list;
  58.     int* list2 = list + size/2;
  59.     int size1 = size/2;
  60.     int size2 = size - size/2;
  61.     mergeSort(list1, size1);
  62.     mergeSort(list2, size2);
  63.     int* list3 = merge(list1, list2, size1, size2);
  64.     int i;
  65.     for(i=0; i<size; i++) {
  66.         list[i] = list3[i];
  67.     }
  68. }
  69.  
  70. int main(int argc, char **argv) {
  71.     srand(time(NULL));
  72.     int size;
  73.     int *lijst = generateRandomList(LIST_SIZE);
  74.     printf("Lijst : ");
  75.     printList(lijst,LIST_SIZE);
  76.     mergeSort(lijst, LIST_SIZE);
  77.     printf("Merged:  ");
  78.     printList(lijst,LIST_SIZE);
  79.     return 0;
  80. }
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