Java to find the second largest element of the array example _java

Source: Internet
Author: User
Tags array example

Assume that all numbers in the array are non-negative integers, and that all digits are different.

Copy Code code as follows:

Package array;

public class Secondmaxelem {

public static int Getsecondmaxelem (int[] array) {

if (array = null | | Array.Length <= 1) {
return-1;
}

int max = array[0] > array[1]? ARRAY[0]: array[1];
int Secmax = array[0] + array[1]-max;
int len = Array.Length;
for (int i = 2; i < Len; i++) {
int cur = array[i];
if (cur > Secmax) {
Secmax = cur;

if (Secmax > Max) {//Swap
int temp = Secmax;
Secmax = max;
max = temp;
}
}
}

return Secmax;
}

public static int getSecondMaxElem2 (int[] array) {

if (array = null | | Array.Length <= 1) {
return-1;
}

int max = array[0] > array[1]? ARRAY[0]: array[1];
int Secmax = array[0] + array[1]-max;
int len = Array.Length;
for (int i = 2; i < Len; i++) {
int cur = array[i];
if (cur > Max) {
Secmax = max;
max = cur;
}
else if (cur > Secmax && cur < max) {
Secmax = cur;
}
else {
Other cases the maximum and the second largest value unchanged, you can draw an axis
}
}

return Secmax;
}

public static void Main (string[] args) {
int[] array = new int[] {};
/* SYSTEM.OUT.PRINTLN ("Algorithm 1:" + Getsecondmaxelem (array));
SYSTEM.OUT.PRINTLN ("Algorithm 2:" + getSecondMaxElem2 (array));

Array = new int[] {2};
SYSTEM.OUT.PRINTLN ("Algorithm 1:" + Getsecondmaxelem (array));
SYSTEM.OUT.PRINTLN ("Algorithm 2:" + getSecondMaxElem2 (array));

Array = new int[] {2, 3, 1, 6, 7, 5, 9};
SYSTEM.OUT.PRINTLN ("Algorithm 1:" + Getsecondmaxelem (array));
SYSTEM.OUT.PRINTLN ("Algorithm 2:" + getSecondMaxElem2 (array));

/* array = new int[] {1, 2, 3, 3, 4, 5, 5};
SYSTEM.OUT.PRINTLN ("Algorithm 1:" + Getsecondmaxelem (array));
SYSTEM.OUT.PRINTLN ("Algorithm 2:" + getSecondMaxElem2 (array));

}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.