Hello, i need to find second largest number in array.
my txt file
5.7 -1 8.6 9.2 15.3 17
And I dont understand how I need to do it? Here's my code but I find only the largest number :(
A[n-1];
1 2 3 4 5 6
double max = 0
for(int i = 0; i < n; i++){
if(max<A[i]){
max = A[i];
}
}
Simple (though not most efficient way) is the following:
remember along with "max" its index "maxI" (or you can remember only it instead of "max" at all).
After passing through array, swap largest element (that's why you need its index) with the first (or with the last).
Then perform similar operation of selecting maximum on the remaining part of array.
------------
Other variant is to add "max2" variable to your code and compare each element firstly with "max" - if it is greater, "max" is shifted to "max2" and new element to "max" - otherwise compare it with "max2" and replace only "max2" with it if necessary.