uni

University stuff
git clone git://git.margiolis.net/uni.git
Log | Files | Refs | README | LICENSE

arrhandler.c (1559B)


      1 #include "arrhandler.h"
      2 
      3 int *fill_array(int N, FILE *dataFile)
      4 {
      5     int num, i = 0;
      6     int *arr = (int *)malloc(N * sizeof(int));
      7 
      8     if (arr == NULL)
      9     {
     10         set_color(BOLD_RED);
     11         printf("Error! Not enough memory, exiting...\n");
     12         exit(EXIT_FAILURE);
     13         set_color(STANDARD);
     14     }
     15     else
     16     {    
     17         do
     18         {
     19             fscanf(dataFile, "%d\n", &num);
     20 
     21             if (num >= 1 && num <= 49)
     22             {
     23                 if (i == 0) { *(arr + i) = num; i++; }
     24                 else if (!exists_in_array(arr, N, num)) { *(arr + i) = num; i++; }
     25             }
     26         } while (i < N);
     27     }
     28 
     29     return arr;
     30 }
     31 
     32 
     33 bool exists_in_array(int *arr, int N, int num)
     34 {
     35     int *arrEnd = arr + (N - 1);
     36     while (arr <= arrEnd && *arr != num) arr++;
     37     return (arr <= arrEnd) ? true : false;
     38 }
     39 
     40 
     41 void quicksort(int *arr, int low, int high)
     42 {
     43     if (low < high) 
     44     { 
     45         int partIndex = partition(arr, low, high); 
     46         quicksort(arr, low, partIndex - 1); 
     47         quicksort(arr, partIndex + 1, high);
     48     }
     49 }
     50 
     51 
     52 int partition(int *arr, int low, int high)
     53 {
     54     int pivot = *(arr + high);
     55     int i = (low - 1), j;
     56   
     57     for (j = low; j <= high - 1; j++) 
     58         if (*(arr + j) < pivot) 
     59             swap(arr + ++i, arr + j); 
     60 
     61     swap(arr + (i + 1), arr + high); 
     62     return (i + 1); 
     63 }
     64 
     65 
     66 void swap(int *a, int *b)
     67 {
     68     int temp = *a;
     69     *a = *b;
     70     *b = temp;
     71 }
     72 
     73 
     74 int find_pos(int *arr, int numIter, int val)
     75 {
     76 	int pos, i;
     77 
     78 	for (i = 0; i < numIter; i++)
     79 		if (val == *(arr + i))
     80 			pos = i;
     81 
     82 	return pos;
     83 }