Skip to content

Instantly share code, notes, and snippets.

@olegon
Last active January 17, 2017 12:22
Show Gist options
  • Save olegon/6230d56c937f37d5650b02e7d6cc5077 to your computer and use it in GitHub Desktop.
Save olegon/6230d56c937f37d5650b02e7d6cc5077 to your computer and use it in GitHub Desktop.
#include <stdio.h>
void minmax(int *v, int n, int *min, int *max);
int main (void) {
int v[5] = { -1, 7, -3, 11, 4 };
int min, max;
minmax(v, 5, &min, &max);
printf("Min: %d\n", min);
printf("Max: %d\n", max);
return 0;
}
/*
Dado um vetor de inteiros v, um inteiro n >= 1 e dois ponteiros para inteiros *min e *max,
atribui o menor valor do vetor v[0..n-1] para *min e
atribui o maior valor do vetor v[0..n-1] para *max.
*/
void minmax(int *v, int n, int *min, int *max) {
if (n == 1) {
*min = v[0];
*max = v[0];
}
else {
minmax(v, n - 1, min, max);
/* Invariante: min e max possem o menor e o maior valor, respectivamente, do vetor v[0..n-2] */
if (v[n - 1] > *max) *max = v[n - 1];
if (v[n - 1] < *min) *min = v[n - 1];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment