0

how to find out the maximum and the second maximum number from an array of integers

5
Contributors
7
Replies
8
Views
10 Years
Discussion Span
Last Post by Rashakil Fol
0

>how to find out the maximum and the second maximum number from an array of integers

You sort them out in ascending order and then you pick the last two.

0

So, assuming you aren't using arrays with thousands of elements, you can use this

do
  swap = 0;
    for (int i=0;i<n-1;i++) // n- nr of elements
     if (anArray[i]>anArray[i+1])
     {
         temp = anArray[i];
         anArray[i] = anArray[i+1];
         anArray[i+1] = temp;
         swap = 1; 
      }
while (swap)

This is the code of the bubble sort. The biggest element will be the last in the array, so the answer to your question (is Chuck Norris :P)

max  = anArray[n];
max2 = anArray[n-1];
0

Here I Present The Code Mr.

void main()
{
  int a[10],max1,max2;//Array Size=10
  clrscr();
  printf("Enter The Array Elements");
  max1=a[0];
  max2=a[0];
  for(i=0;i<9;i++)
   {
       if(a[i]>=max1)
          max1=a[i];
   }
   for(i=0;i<9;i++)
   {
       if(a[i]>=max2&&a[i]!=max1)
           max2=a[i];
   }
printf("%d   %d",max1,max2);
 
}
0
void main()

This is unacceptable. main returns a type int.

clrscr();

This is unacceptable. You did not include
the header file for it. Moreover, it makes your code not agreeable
with C standards.

for(i=0;i<9;i++)

You did not declare variable i.

Nevertheless, after fix it in order to compile this is the output that you
get: Enter The Array Elements2009315348 2009312941

Please, abstain of posting code that do not compile, do not work, nor help anyone.
And do not ignore the rules of how to post, nor the advise that you have received already about it.

0

>how to find out the maximum and the second maximum number from an array of integers

You sort them out in ascending order and then you pick the last two.

Use a heap ^_^ to store the top two elements as you walk through the array. Then finding the top K elements takes O(N log K) time instead of O(N log N).

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.