Casa > H > How To Find The Largest And Smallest Number In An Unsorted Integer Array

How to find the largest and smallest number in an unsorted integer array

If the array is unsorted, you must read every value in the array and use a variable for the min and max value found. Here is an example in C/C++.

// Include for printf function

#include

int main()

{

// Declare variables and a random sequence of 10 integers

// greater than zero

int maxValue = -2147483647; // initialize to smallest possible value

int minValue = 2147483647; // initialize to largest possible value

// sequence is an array to hold the ten numbers

int sequence[14] = { -10, 3, 7, 9, 20, 6, 4, 1, 8, 10, -30, 62, 5, 2 };

// Look at every value in the sequence and compare it

// to the min and max values

for (int index = 0; index < 14; ++index) {

// If the number in the sequence at this location

if (maxValue < sequence[index]) {

maxValue = sequence[index]; // save the new largest value

}

if (minValue > sequence[index]) {

minValue = sequence[index]; // save the new smallest value

}

}

printf("The Maximum Value = %d and the Smallest Value = %d\n", maxValue, minValue);

return 0;

}

De Ahron

Quais são os recursos ocultos disponíveis no dispositivo Amazon Echo Studio? :: Qual é a diferença entre TubeMate e Vidmate?