[ create a new paste ] login | about

Link: http://codepad.org/BoLhqtzv    [ raw code | output | fork ]

C, pasted on Apr 26:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

#define M 10

/* This function generates an array of random integers in the range [0,M-1] of length n. */
int* random_array(const int n) {
  int *x;
  int i;

  x = (int*) malloc(n * sizeof(int));

  srand(time(NULL ));

  for (i = 0; i < n; i++) {
    x[i] = rand() % M;
  }

  return x;
}

/* print an array. */
void print_array(const int n, const int *x) {
  int i;

  printf("array: ");
  for (i = 0; i < n && i < 32; i++) {
    printf("%d ", x[i]);
  }
  if (n > 32) {
    printf("...");
  }
  printf("\n");
}

/* check if a given array is sorted in ascending order. */
void is_sorted(const int n, const int *x) {
  int i;

  for (i = 1; i < n; i++) {
    if (x[i - 1] > x[i]) {
      fprintf(stderr, "ERROR: Array is not sorted!\n");
      return;
    }
  }
  printf("Array is sorted!\n");
}

/* n is the length of the array x and m is the same m as on your exercise sheet.
 * In this case m is set to 10. */
void sort(const int n, int *x, int m) {
  /* allocates memory for an zero initialized array */
    int *muh = (int*) calloc(m, sizeof(int));
    int loop; //count variable
    
	/*counts each number in the array*/
    for(loop = 0; loop < n; loop++){
        muh[x[loop]]++;
    }
    
	/*Overrides x, Each number appears muh[loop] times at the beginning of line 65*/
    for(loop = 0; loop < n; loop++){
		for(; muh[loop] > 0; muh[loop]--) {
			*(x++) = loop;
       }
    }
}

int main() {
  int *x;
  int n;

  /* set length of the arrays */
  n = 1 << 5;

  /* get a random integer array of length n */
  x = random_array(n);

  /* print the unsorted array */
  print_array(n, x);

  printf("\n");
  printf("sorted array:\n");

  /* sort x by using sort, check if it is sorted and print it out */
  sort(n, x, M);
  is_sorted(n, x);
  print_array(n, x);

  return 0;
}


Output:
1
2
3
4
5
array: 8 3 4 0 4 1 8 7 1 0 3 7 3 0 3 1 9 4 0 9 4 2 2 4 8 5 7 2 4 1 8 3 

sorted array:
Array is sorted!
array: 0 0 0 0 1 1 1 1 2 2 2 3 3 3 3 3 4 4 4 4 4 4 5 7 7 7 8 8 8 8 9 9 


Create a new paste based on this one


Comments: