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;
}
Artigos semelhantes
- Is it possible to have a league with an odd number of teams while making sure each team plays the same number of games?
- Como podemos converter um array unidimensional para um array bidimensional em Python?
- How to write an algorithm in pseudocode that displays the sum of 5 numbers entered by the user and displays the smallest of the 5 numbers
- How to find my UPS account number