how to find 2nd largest array if array values like{10,20,92,81,92,34}

Recommended Answers

All 3 Replies

  int[] arr = {10, 20, 91, 81, 92, 34};
  //let pretend  that the largest number is 10 
        int maxVal = arr[0];
        int secLargestNum = 0;
        for (int i = 1; i < arr.length; i++) {
 //check if the number at the postion i is greater than the    maxVal which is 10 
            if (arr[i] >= maxVal) {
            //if the condation is true then assign secLargestNum to maxVal .. now secLargestNum will become 10  
                secLargestNum = maxVal;
                maxVal = arr[i];

            } else if (arr[i] > secLargestNum) {

                secLargestNum = arr[i];


            }
        }

        System.out.println(secLargestNum);

I tried with array 10,20,92,81,92,34 but it didn't seem to work

I hope this will get you start on something .. if I figure out another solution I will update the answer

commented: Don't give answers. Help them if they attempt the question themselves. +0

sk8ergirl: don't spoonfeed, just explain the possible algorithms to go through.
anjijava16: either sort the array and take the element with the second highest index, or iterate over the array for each element (if you really are not allowed to sort the array, which I doubt) until you've found an element that has only one value higher than the value of the element you're checking for.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.