sav

Sorting Algorithms Visualized
Index Commits Files Refs README LICENSE
array.c (1498B)
   1 #include "array.h"
   2 
   3 #include <stdio.h>
   4 #include <time.h>
   5 
   6 static void (*shuffle_handler[MAX_SHUFFLE])(Arr *arr) = {
   7     &arr_in_order,
   8     &arr_reversed,
   9     &arr_random
  10 };
  11 
  12 status_t Arr_create(Arr **arr) {
  13     if(((*arr) = (Arr *)malloc(sizeof(Arr))) == NULL)
  14         return ERROR_MEMORY_ALLOC;
  15 
  16     if(((*arr)->v = malloc(sizeof(int) * (ARR_LEN + 4))) == NULL)
  17         return ERROR_MEMORY_ALLOC;
  18 
  19     if(((*arr)->bk = malloc(sizeof(int) * (ARR_LEN + 4))) == NULL)
  20         return ERROR_MEMORY_ALLOC;
  21 
  22     (*arr)->len = ARR_LEN;
  23     (*arr)->shuffle = &arr_shuffle;
  24 
  25     return OK;
  26 }
  27 
  28 void Arr_destroy(Arr *arr) {
  29     free(arr->bk);
  30     free(arr->v);
  31     free(arr);
  32 }
  33 
  34 void arr_restore_from_bk(Arr *arr) {
  35     for(size_t i = 0; i < arr->len; i++)
  36         arr->v[i] = arr->bk[i];
  37 }
  38 
  39 void arr_random(Arr *arr) {
  40     srand((unsigned int)time(NULL));
  41     for(size_t i = 0; i < arr->len; i++)
  42         while(!(arr->v[i] = arr->bk[i] = rand() % ARR_MAX));
  43 
  44     printf("ARRAY: Shuffling array done\n");
  45 }
  46 
  47 void arr_reversed(Arr *arr) {
  48     size_t i;
  49     int per_element;
  50 
  51     per_element = (ARR_MAX / arr->len);
  52     for(i = 0; i < arr->len; i++)
  53         arr->v[i] = arr->bk[i] = (arr->len * per_element) - (i * per_element);
  54 }
  55 
  56 void arr_in_order(Arr *arr) {
  57     size_t i;
  58     int per_element;
  59 
  60     per_element = (ARR_MAX / arr->len);
  61 
  62     for(i = 0; i < arr->len; i++)
  63         arr->v[i] = arr->bk[i] = (i * per_element);
  64 }
  65 
  66 void arr_shuffle(Arr *arr) {
  67     shuffle_handler[arr->shuffle_sel](arr);
  68 }
  69 
  70 void arr_shuffle_next(Arr *arr) {
  71     arr->shuffle_sel = ((arr->shuffle_sel + 1) == MAX_SHUFFLE) ? 0 : arr->shuffle_sel + 1;
  72 }