HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Max and Min in array using minimum comparisons

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arrayminimumminmaxusingandcomparisons

Problem

Is this the most robust and fastest way for finding the min and max out of an array without using STL functions? How can I improve it?

#include 
#include 
int main(int argc, char const *argv[]) {
system("clear");
int c=9,n[10],max,min,i;
while (c>=0) {
n[c]=random()%100;
printf("%d\n",n[c]);
c--;}c=10;
max=n[0];min=n[1];
for ( i =0; in[i])min=n[i];
}
printf("\n%d\n%d\n",max,min);
return 0;
}

Solution

First of all, format your code. Indentation goes along way. If everything is left-justified, you can't make out any of the logic.

Secondly, this is a good idea:

max=n[0];min=n[1];


But we should really initialize both to n[0], and on separate lines:

max = n[0];
min = n[0];


The reason is this allows us to start at index 1:

for (i=1; i max) {
        max = n[i];
    }
    else if (n[i] < min) {
        min = n[i];
    }
}


We could also consider putting this into a function:

void minmax(int* arr, int len, int* min, int* max) { ... }

minmax(n, c, &min, &max);


Any time you're doing something k times for some constant, or filling in an array - do it front to back. It will be much easier to understand. Don't fill n from index 9 to 0... fill it from 0 to 9. Also, prefer a for loop to a while loop and use i both times:

int c=10, n[10];
for (i=0; i<c; ++i) {
}


And lastly, c is a bad name for the max size of your array. Something like SIZE or LENGTH or anything to that effect would be better.

Code Snippets

max=n[0];min=n[1];
max = n[0];
min = n[0];
for (i=1; i<c; ++i) {
    if (n[i] > max) {
        max = n[i];
    }
    else if (n[i] < min) {
        min = n[i];
    }
}
void minmax(int* arr, int len, int* min, int* max) { ... }

minmax(n, c, &min, &max);
int c=10, n[10];
for (i=0; i<c; ++i) {
}

Context

StackExchange Code Review Q#107335, answer score: 3

Revisions (0)

No revisions yet.