uni

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

arrhandler.c (1742B)


      1 #include "arrhandler.h"
      2 
      3 int *fill_array(int N)
      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             printf("arr[%d]: ", i);
     20             scanf("%d", &num);
     21 
     22             if (num >= 1 && num <= 49)
     23             {
     24                 if (i == 0) { *(arr + i) = num; i++; }
     25                 else
     26                 {
     27                     if (!exists_in_array(arr, N, num)) { *(arr + i) = num; i++; }
     28                     else printf("Give a different number.\n");
     29                 }
     30             }
     31             else printf("Give a number in [1, 49].\n");
     32         } while (i < N);
     33     }
     34 
     35     return arr;
     36 }
     37 
     38 
     39 bool exists_in_array(int *arr, int N, int num)
     40 {
     41     int *arrEnd = arr + (N - 1);
     42     while (arr <= arrEnd && *arr != num) arr++;
     43     return (arr <= arrEnd) ? true : false;
     44 }
     45 
     46 
     47 void quicksort(int *arr, int low, int high)
     48 {
     49     if (low < high) 
     50     { 
     51         int partIndex = partition(arr, low, high); 
     52         quicksort(arr, low, partIndex - 1); 
     53         quicksort(arr, partIndex + 1, high);
     54     }
     55 }
     56 
     57 
     58 int partition(int *arr, int low, int high)
     59 {
     60     int pivot = *(arr + high);
     61     int i = (low - 1), j;
     62   
     63     for (j = low; j <= high - 1; j++) 
     64         if (*(arr + j) < pivot) 
     65             swap(arr + ++i, arr + j); 
     66 
     67     swap(arr + (i + 1), arr + high); 
     68     return (i + 1); 
     69 }
     70 
     71 
     72 void swap(int *a, int *b)
     73 {
     74     int temp = *a;
     75     *a = *b;
     76     *b = temp;
     77 }
     78 
     79 
     80 int find_pos(int *arr, int numIter, int val)
     81 {
     82 	int pos, i;
     83 
     84 	for (i = 0; i < numIter; i++)
     85 		if (val == *(arr + i))
     86 			pos = i;
     87 
     88 	return pos;
     89 }