1

my question is that I need to find the second largest value from my array but I am getting the same value which is equal to the first value. please help

int[] nums = { 50, 6, 60, 70, 80, 90, 9, 150, 2, 35 };
int max = 0;
int secmax = 0;

for (int x = 0; x < nums.length; x++) {
    if (nums[x] > max)
        max = nums[x];
    if (nums[x] > secmax && secmax != max)
        secmax = nums[x];
}

System.out.println("1st H value: " + max);
System.out.println("2nd H Value: " + secmax);

8 Answers 8

7

your mistake is the conditions in the loop use this code:

public class Main{
    public static void main(String[] args){
        int[] nums = { 6, 9, 11, 1, 10 };

        int max = Integer.MIN_VALUE;
        int secmax = Integer.MIN_VALUE;

        for(int x=0; x<nums.length; x++) {
            if(nums[x]>max ) {
                secmax = max;
                max=nums[x];
            }else if(nums[x]>secmax){
                secmax=nums[x];
            }
         }
        System.out.println("1st H value: " + max);
        System.out.println("2nd H Value: " + secmax);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I think you should also take into consideration the value of 'secmax' variable in the above snippet. For eg: The above solution would simply fail for the test values 6 9 11 1 10
1

You should use if.. else if structure inside your for loop:

for (int item : nums) {
    if (item > max) {
        secmax = max;
        max = item;
    } else if (item > secmax) {
        secmax = item;
    }
}

Run time of this algorithm is O(n). There is also quite concise solution in case the array is sorted:

Arrays.sort(nums);     // Dual-Pivot Quicksort O(nlogn)
System.out.println(nums[nums.length - 1]);    // largest item
System.out.println(nums[nums.length - 2]);    // second largest item
...

You can get any n-largest item, but in this case the run time will be O(nlogn)

Comments

1

This could be the simplest one

public static void main(String[] args) {
    int[] array = { 1, 2, 3, -1, -2, 4 };
    Arrays.sort(array);
    System.out.println(array[array.length-2]);
    
}

Comments

0

Step 1:

Iterate the given array

Step 2 (first if condition arr[i] > largest):

If current array value is greater than largest value then

Move the largest value to secondLargest and make

current value as largest

Step 3 (second if condition arr[i] > secondLargest )

If the current value is smaller than largest and greater than secondLargest then the current value becomes secondLargest

public class SecondLargest {

        public static void main(String[] args) {

            int arr[] = {50,06,60,70,80,90,9,150,2,35};
            int largest = arr[0];
            int secondLargest = arr[0];

            System.out.println("The given array is:" );
            for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i]+"\t");
            }
            for (int i = 0; i < arr.length; i++) {

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

                } else if (arr[i] > secondLargest) {
                    secondLargest = arr[i];

                }
            }

            System.out.println("\nSecond largest number is:" + secondLargest);

        }
    }

output :

The given array is:
50  6   60  70  80  90  9   150 2   35  
Second largest number is:90

Comments

0
int max=nums[0],secMax=nums[0]      
for (int x = 0; x < nums.length; x++) {
    if (nums[x] > max) {
        secMax=max;
        max = nums[x];
    }
}

secMax wil have the second largest

Comments

0
  1. Initialize max and scmax(second max) with 2 first value of array
  2. Then I compare the rest with max and possibly scmax. at each comparison I adjust.
int arr[] = {-50,10,80,78,67,86,34,276,8};
        int max, scmax;
        if(arr[0]>=arr[1]){
            max = arr[0]; scmax=arr[1];}
        else{max = arr[1]; scmax=arr[0];}

        for (int i = 2; i < arr.length; i++) {
            if (max <= arr[i]) {
                scmax = max;
                max = arr[i];
            } else if(scmax<=arr[i]){ scmax = arr[i];}
        }
            System.out.println("max"+max);
         System.out.println("scmax"+scmax);



4 Comments

Some explanation of the answer would be helpful together with the logic/reason why this answers the question.
I have a little trouble with the interface, i'm just starting on this platform(sorry). the idea is that i initialize max and scmax with the first two values ​​of the array. then when if i find a value greater than max, it becomes max and the old max becomes scmax
While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
Thank you for notice! i edited and change the code.
0
public class Secondlargest {
public static void main(String[] args) {
    int arr[]= {5,3,6,8,9,11,5,74};
    List <Integer> array = new ArrayList<Integer> ();

    for(int i=0;i<arr.length;i++){
        if (array.isEmpty()){
            array.add(arr[i]);
        }
        else if(array.contains(arr[i])) {
        }
        else{
            array.add(arr[i]);
        }
    }

    Collections.sort(array);
    System.out.println("Second Largest "+ array.get(array.size()-2));
}

}

Comments

0

Very easy answer using java streams

public static int secondLargestNumberInArray(Integer[] numbers) {
    return Arrays.stream(numbers).sorted(Collections.reverseOrder()).skip(1).findFirst().get();
}

In case you want to use primitive method parameter

public static int secondLargestNumberInArray(int[] numbers) {
    Integer[] arr = new Integer[numbers.length];
    Arrays.setAll(arr, i -> numbers[i]);
    return Arrays.stream(arr).sorted(Collections.reverseOrder()).skip(1).findFirst().get();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.