2

Hi all I want to find out second Largest no in Array accept negative numbers. I have used following code and this display second largest no of only positive no.So please suggest me how to do this.

class ArrayExample {
    public static void main(String[] args) {
        int secondlargest = 0;
        int largest = 0;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter array values: ");
        int arr[] = new int[5];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = input.nextInt();
            if (largest < arr[i]) {
                secondlargest = largest;
                largest = arr[i];
            }
            if (secondlargest < arr[i] && largest != arr[i])
                secondlargest = arr[i];
        }
        System.out.println("Second Largest number is: " + secondlargest);
    }
}
Dipu
  • 103
  • 1
  • 3
  • 6
  • 4
    What about using a good sorting algorithm and taking the second element? – Salman May 23 '12 at 08:29
  • 4
    @Salman: In the general case, that's unnecessarily expensive (`O (n logn)` rather than `O(n)`). Of course, if the input is always of length five, the choice of algorithm is moot. – NPE May 23 '12 at 08:30
  • similar thread http://stackoverflow.com/questions/2615712/finding-the-second-highest-number-in-array – Nandkumar Tekale May 23 '12 at 08:33
  • I'd assume that "no" is short for "number" – Buhb May 23 '12 at 08:45

9 Answers9

7

The problem comes from the fact that you initialize your two variables to 0 in the lines:

int secondlargest = 0;
int largest = 0;

You should instead initialize them to Integer.MIN_VALUE and then it will also work for negative values.

0

Initialize largest and secondLargest to Integer.MIN_VALUE instead of zero.

Hakan Serce
  • 11,198
  • 3
  • 29
  • 48
0

Initialize the variables secondlargest and largest with the smallest negative values.
Use this code:

class ArrayExample {
        public static void main(String[] args) {
            int secondlargest = Integer.MIN_VALUE;
            int largest = Integer.MIN_VALUE;
            Scanner input = new Scanner(System.in);
            System.out.println("Enter array values: ");
            int arr[] = new int[5];
            for (int i = 0; i < arr.length; i++) {
                arr[i] = input.nextInt();
                if (largest < arr[i]) {
                    secondlargest = largest;
                    largest = arr[i];
                }
                if (secondlargest < arr[i] && largest != arr[i])
                    secondlargest = arr[i];
            }
            System.out.println("Second Largest number is: " + secondlargest);
        }
    }
Jainendra
  • 24,713
  • 30
  • 122
  • 169
0

This works for me, for both positive and negative values. Before the loop, you need to initialize the largest and secondlargest variables with very small values, by doing this you can be (almost) sure that all the other values in the array will be greater than them:

int largest = Integer.MIN_VALUE;
int secondlargest = Integer.MIN_VALUE;

Inside the loop:

if (arr[i] > largest) {
    secondlargest = largest;
    largest = arr[i];
}

else if (arr[i] != largest && arr[i] > secondlargest) {
    secondlargest = arr[i];
}

After the loop:

if (secondlargest != Integer.MIN_VALUE)
    System.out.println("Second Largest number is: " + secondlargest);

Notice that the last check is required for the (rather unlikely) case where all the elements in the array happen to be Integer.MIN_VALUE.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
0

I think this method may be useful it takes around n+log(n)-2 comparisons

 import java.util.ArrayList;


 public class SecondLargest {
 static ArrayList<ArrayList<Integer>> level = new ArrayList<ArrayList<Integer>>();

public static void main(String[] args) {
    int input[]={9,8,7,4,5,6,1,2,3,1,1,21,33,32,1,2,3,12,3,2,1};
    ArrayList<Integer> arr= new ArrayList<Integer>();

    for(int i=0;i<input.length;i++){
        arr.add(input[i]);
    }
    level.add(arr);
    seconLarger(arr);
    System.out.println(SecondLarge(level));
}

private static ArrayList<Integer> seconLarger(ArrayList<Integer> arr) {
    ArrayList<Integer> tmp= new ArrayList<Integer>();
    if (arr.size()==1)
    {
        return arr;
    }

if(arr.size()%2==0)
    {
        for(int i=0;i<arr.size();i=i+2)
        {
            if(arr.get(i)>arr.get(i+1))
            {
                tmp.add(arr.get(i));
            }
            else
            {
                tmp.add(arr.get(i+1));
            }
        }


    }   
else 
    {
        for(int i=0;i<arr.size()-1;i=i+2)
        {
            if(arr.get(i)>arr.get(i+1))
            {
                tmp.add(arr.get(i));
            }
            else
            {
                tmp.add(arr.get(i+1));
            }
        }
        tmp.add(arr.get(arr.size()-1));
    }
level.add(tmp);
return seconLarger(tmp);
}

private static int SecondLarge(ArrayList<ArrayList<Integer>> li)
{
    int li_size=li.size();
    int large=li.get(li_size-1).get(0);
    int secondlarge=0;
    int tmp=0;
    for(int i=li_size-2;i>=0;i--)
    {
        ArrayList<Integer> arr = li.get(i);
        if(large==arr.get(tmp))
        {
            if(tmp+1<arr.size())
            {
                if(secondlarge<arr.get(tmp+1))
                {
                    secondlarge=arr.get(tmp+1);
                }
            }
        }
        else
        {
            if(secondlarge<arr.get(tmp))
            {
                secondlarge=arr.get(tmp);
            }
            tmp=tmp+1;

        }

        tmp=tmp*2;
    }
    return secondlarge;
}}
Ravi Teja N
  • 145
  • 2
  • 12
0
package com.demo.mum;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author cyruses
 * 
 */
public class SecondLargest {
    public static int largest = Integer.MIN_VALUE;
    public static int secondLargest = Integer.MIN_VALUE;

    public static void main(String args[]) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the Size of Array:");
        int n = Integer.parseInt(br.readLine());
        int a[] = new int[n];
        System.out.println("Enter the elements on array:");
        for (int i = 0; i < a.length; i++) {
            a[i] = Integer.parseInt(br.readLine());
        }
        System.out.println("Elements you entered are:");
        for (int i = 0; i < a.length; i++) {
            System.out.println("a[" + i + "]" + "=" + a[i]);
        }
        if (a.length <= 2) {
            if (a[0] == a[1]) {
                System.out.println("Theres no second largest number in your array");
            } else {
                System.out.println("SecondLargest:" + secondLargest(a));
            }
        } else {
            System.out.println("SecondLargest:" + secondLargest(a));
        }
    }

    private static int secondLargest(int[] a) {

        for (int i = 0; i < a.length; i++) {
                if (a[i] > largest) {
                    secondLargest = largest;
                    largest = a[i];
                } else if (a[i] > secondLargest) {
                    secondLargest = a[i];
                }
            }
        return secondLargest;
    }
}
Cyruses Cyrus
  • 109
  • 1
  • 6
0

Or here is a gimmicky Java implementation which doesn't rely on Integer.MIN_VALUE

int findSecondHighest(int[] arr){
    if(arr == null || arr.length < 2){
        throw new IllegalArgumentException();
    }

    int fh,sh;

    if(arr[0]>=arr[1]){
        fh = arr[0];
        sh = arr[1];
    }else{
        fh = arr[1];
        sh = arr[0];
    }

    for (int i = 2; i < arr.length; i++) {
        if(fh < arr[i]){
            sh = fh;
            fh = arr[i];
        }else if(sh < arr[i]){
            sh = arr[i];
        }
    }

    return sh;
}
Tunaki
  • 132,869
  • 46
  • 340
  • 423
rocketboy
  • 9,573
  • 2
  • 34
  • 36
0

Instead of initializing the second largest number to min value or zero. You can follow below code to get second largest number.

import java.util.Scanner;

public class SecondLargestNumber {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] a;
        int n;
        System.out.println("Enter number of elements");
        n = scanner.nextInt();
        a = new int[n];
        for(int i=0; i<n; i++) {
            a[i] = scanner.nextInt();
        }
        int secondLargestNumber = a[0];
        int largestNumber = a[0];
        int count = 1;
        for(int i=1; i<a.length; i++) {
            if(a[i] >= largestNumber) {
                if(a[i] == largestNumber) {
                    count++;
                } else {
                    count = 1;
                }
                secondLargestNumber = largestNumber;
                largestNumber = a[i];
            } else {
                if(secondLargestNumber == largestNumber && count == 1) {
                    secondLargestNumber = a[i];
                } else if(a[i] > secondLargestNumber) {
                    secondLargestNumber = a[i];
                }
            }
        }
        System.out.println("Second Largest Number: " + secondLargestNumber);
    }
}
manohar e
  • 327
  • 3
  • 6
  • 16
0
public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    System.out.println("Enter array size = ");
    int size=in.nextInt();
    int[] n = new int[size];
    System.out.println("Enter "+ size +" values ");

    for(int i=0;i<n.length;i++)
        n[i] = in.nextInt();
    int big=n[0],sbig=n[0];

    // finding big, second big
    for(int i=0;i<n.length;i++){
        if(big<n[i]){
            sbig=big;
            big=n[i];
            }else if(sbig<n[i])
                sbig=n[i];
    }
    // finding second big if first element itself big
    if(big==n[0]){
        sbig=n[1];
        for(int i=1;i<n.length;i++){
            if(sbig<n[i]){
                sbig=n[i];
                }
        }
    }       

    System.out.println("Big "+ big+" sBig "+ sbig);

    in.close();
}
girish
  • 1