9511_workbook

solved exercises from algorithms & programming I (9511) prof. Cardozo
Index Commits Files Refs README
guia03/ex34.c (849B)
   1 #include <stdio.h>
   2 #include <stdbool.h>
   3 
   4 #define N 10
   5 
   6 bool isSorted(int *vector, size_t size);
   7 bool isSortedBothDirections(int *vector, size_t size);
   8 
   9 int main (void) 
  10 {
  11     int vector[N] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
  12     int vectorInv[N] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
  13 
  14     printf("The vector is sorted: %s\n", isSorted(vector, N) ? "Yes" : "No");
  15     printf("The vector is sorted: %s\n", isSortedBothDirections(vector, N) ? "Yes" : "No");
  16 
  17     return 0;
  18 }
  19 
  20 
  21 bool isSortedBothDirections(int *vector, size_t size)
  22 {
  23     size_t i, j, k;
  24     i = j = k = 1;
  25 
  26     while(i < size) {
  27         j += (vector[i] >= vector[i - 1]);
  28         k += (vector[i] <= vector[i - 1]);
  29         i++;
  30     }
  31 
  32     return true * (j == size) + true * (k == size);
  33 }
  34 
  35 bool isSorted(int *vector, size_t size)
  36 {
  37     size_t i;
  38     for(i = 1; (i < size) && (vector[i] >= vector[i - 1]); i++)
  39         ;
  40 
  41     return true * (size == i);
  42 }
  43