How to find second largest number in an array in Java? - java

I'm just practicing some MIT java assignments. But, I'm not sure how to find the second largest number. http://ocw.csail.mit.edu/f/13
public class Marathon {
public static void main(String[] arguments) {
String[] names = { "Elena", "Thomas", "Hamilton", "Suzie", "Phil",
"Matt", "Alex", "Emma", "John", "James", "Jane", "Emily",
"Daniel", "Neda", "Aaron", "Kate" };
int[] times = { 341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412,
393, 299, 343, 317, 265 };
for (int i = 0; i < names.length; i++) {
System.out.println(names[i] + ": " + times[i]);
}
System.out.println();
System.out.println("Largest Timing " + Largest(times));
System.out.println();
}
public static int Largest(int[] times) {
int maxValue = times[0];
for (int i = 1; i < times.length; i++) {
if (times[i] > maxValue) {
maxValue = times[i];
}
}
return maxValue;
}
}

Instead of resorting to sorting the array, you can simply do the following:
Keep a largestValue and a secondLargestValue
Loop through the entire array once, for each element:
Check to see if the current element is greater than largestValue:
If so, assign largestValue to secondLargestValue, then assign the current element to largestValue (think of it as shifting everything down by 1)
If not, check to see if the current element is greater than secondLargestValue
If so, assign the current element to secondLargestValue
If not, do nothing.
O(n) run time
O(1) space requirement

Sorting the array simply to find an order statistics is too wasteful. You can find the second largest element by following an algorithm that resembles the one that you already have, with an additional variable representing the second largest number.
Currently, the next element could be larger than the max or equal to/smaller than the max, hence a single if is sufficient:
if (times[i] > maxValue) {
maxValue = times[i];
}
With two variables to consider, the next element could be
Greater than the max - the max becomes second largest, and the next element becomes the max
Smaller than the max but greater than the second largest - the next element becomes second largest.
A special care must be taken about the initial state. Look at the first two items, and assign the larger one to the max and the smaller to the second largest; start looping at the element number three, if there is one.
Here is how you can code it:
if (times[i] > maxValue) {
secondLargest = maxValue;
maxValue = times[i];
} else if (times[i] > secondLargest) {
secondLargest = times[i];
}

Generally speaking:
Have two values -- "largest" and "notQuite".
Initialize both to -9999 or whatever.
Scan through your list. If the number is larger than "largest", set "largest" to that number. But before you do that, copy the old "largest" value to "notQuite".
If, on the other hand, the number is smaller than "largest" but is larger than "notQuite", set "notQuite" to that number.
When you're done examining all the numbers, "notQuite" contains the second-largest.
And note that, as you fill in the above numbers, you can also keep a "largestIndex" and "notQuiteIndex" and fill those in with the corresponding array index values, so you can identify the "winning" value. Unfortunately, though, if there are multiple identical "largest" or "secondLargest" values the simple index scheme doesn't work and you need to keep a list of some sort.

private static int secLargest(int[] numbers) {
int maxVal = 0;
int nextMaxVal = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] > maxVal) {
nextMaxVal = maxVal;
maxVal = numbers[i];
}
if (numbers[i] < maxVal) {
nextMaxVal = maxVal;
maxVal = numbers[i];
}
}
return nextMaxVal;
}

private void secondLargest(int arr[]){
int maxOne=arr[0];
int maxTwo=arr[1];
for(int i=0;i<arr.length;i++){
if(arr[i]>maxOne){
maxTwo=maxOne;
maxOne=arr[i];
}else if (arr[i]>maxTwo) {
maxTwo=arr[i];
}
}
System.out.println(maxOne);
System.out.println(maxTwo);
}

int largest=time[0];
int secondLargest=largest;
for(int i=0;i<time.length;i++){
if(time[i]>largest){
secondLargest=largest;
largest=time[i];
}
else if(secondLargest<time[i] && time[i]<largest || secondLargest>=largest)
secondLargest=time[i];
}
return secondLargest;

public void findMax(int a[]) {
int large = Integer.MIN_VALUE;
int secondLarge = Integer.MIN_VALUE;
for (int i = 0; i < a.length; i++) {
if (large < a[i]) {
secondLarge = large;
large = a[i];
} else if (a[i] > secondLarge) {
if (a[i] != large) {
secondLarge = a[i];
}
}
}
System.out.println("Large number " + large + " Second Large number " + secondLarge);
}
The above code has been tested with integer arrays having duplicate entries, negative values. Largest number and second largest number are retrieved in one pass. This code only fails if array only contains multiple copy of same number like {8,8,8,8} or having only one number.

It will also extract second largest number if largest number occours two times as well as in a single for loop.
import java.util.*;
public class SecondLargestInArray
{
public static void main(String[] args)
{
int arr[] = {99,14,46,47,86,92,52,48,36,66,85,92};
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]<largest && arr[i]>secondLargest) || largest==secondLargest)
{
secondLargest=arr[i];
}
}
System.out.println("\nLargest number is:" + largest);
System.out.println("\nSecond largest number is:" + secondLargest);
}
}

Find the second largest element in the given array:
public static void findSecondMax(){
int[] arr = {3, 2, 20, 4, 1, 9, 6, 3, 8};
int max = 0;
int secondMax = 0;
for(int i =0; i< arr.length; i++) {
if(max < arr[i]) max = arr[i];
if((max > arr[i]) && (secondMax < arr[i])) secondMax = arr[i];
}
System.out.println(secondMax);
}

public static void main (String args[]) {
int [] arr = {1,4,3,10,4,8,20,5,33};
int largest = 0;
int secondLargest = 0;
for (int x : arr) {
if (x > largest) {
secondLargest = largest;
largest = x;
}
else if (x > secondLargest) {
secondLargest = x;
}
}
System.out.println("secondLargest:"+secondLargest);
}

Updated : Changed to Java.
class Main {
public static void main(String[] args) {
int a = Integer.MIN_VALUE;
int b = Integer.MIN_VALUE;
int[] arr = {44,6,43,8,9,-10,4,15,3,-30,23};
for(int i=0; i < arr.length; i++){
if( arr[i] > a || arr[i] > b ){
if( a < b ) {
a = arr[i];
} else {
b = arr[i];
}
}
}
int secondLargest = a < b ? a : b;
System.out.println(secondLargest);
}
}

Related

How to display the row with the max value?

I am trying to display the current row that has the max value. So far I have the max value by adding the elements in the array but I am trying to display the specific row it is in. For example:
{4,4,4}
{5,5,5}
:25 is the biggest val possible going by row to row
The max value here would be 15 as my code looks and finds the maximum addition in each row in a 2D array. How would I get my code to display the row {5,5,5} as well as the actual maximum addition that is possible with the given rows.
Here is my current code:
public class review{
int largestRowsSum(int[][] arr){
int sum = 0;
int largest = 0;
for (int i = 0; i < arr.length; i++){
for(int j = 0; j < arr[i].length; j++){
sum += arr[i][j];
}
if(sum > largest){
largest = sum;
}
sum = 0;
}
return largest;
}
}
First, your current method could be simplified and static. Like,
static int largestRowsSum(int[][] arr) {
int sum = Arrays.stream(arr[0]).sum();
for (int i = 1; i < arr.length; i++) {
sum = Math.max(Arrays.stream(arr[i]).sum(), sum);
}
return sum;
}
Second, you could invoke that method and then iterate the array to find the index of the array with the matching sum. Like,
static int largestRowIndex(int[][] arr) {
int target = largestRowsSum(arr);
for (int i = 0; i < arr.length; i++) {
if (Arrays.stream(arr[i]).sum() == target) {
return i;
}
}
return -1;
}
Finally, call that method and use the returned index to display the row and correct sum. Like,
public static void main(String[] args) {
int[][] arr = { { 4, 4, 4 }, { 5, 5, 5 } };
int n = largestRowIndex(arr);
System.out.printf("The largest row is %s and the sum is %d.%n",
Arrays.toString(arr[n]), Arrays.stream(arr[n]).sum());
}
Outputs, the row {5,5,5} as well as the actual maximum, as requested
The largest row is [5, 5, 5] and the sum is 15.

Given an array of arrays, for each inner array - If the array has < 2 numbers, return 0 else return second smallest number [duplicate]

We are required in our assignment to find the second smallest integer in one array recursively. However, for the sake of understanding the subject more, I want to do it iteratively first (with the help of this website) and recursively on my own.
Unfortunately, doing it iteratively is quite confusing. I understand that the solution is simple but i can't wrap my head around it.
Below is my code, so far:
public static void main(String[] args)
{
int[] elements = {0 , 2 , 10 , 3, -3 };
int smallest = 0;
int secondSmallest = 0;
for (int i = 0; i < elements.length; i++)
{
for (int j = 0; j < elements.length; j++)
{
if (elements[i] < smallest)
{
smallest = elements[i];
if (elements[j] < secondSmallest)
{
secondSmallest = elements[j];
}
}
}
}
System.out.println("The smallest element is: " + smallest + "\n"+ "The second smallest element is: " + secondSmallest);
}
This works for a few numbers, but not all. The numbers change around because the inner if condition isn't as efficient as the outer if condition.
Array rearrangements are forbidden.
Try this one. Second condition is used to catch an event when the smallest number is the first
int[] elements = {-5, -4, 0, 2, 10, 3, -3};
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for (int i = 0; i < elements.length; i++) {
if(elements[i]==smallest){
secondSmallest=smallest;
} else if (elements[i] < smallest) {
secondSmallest = smallest;
smallest = elements[i];
} else if (elements[i] < secondSmallest) {
secondSmallest = elements[i];
}
}
UPD by #Axel
int[] elements = {-5, -4, 0, 2, 10, 3, -3};
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for (int i = 0; i < elements.length; i++) {
if (elements[i] < smallest) {
secondSmallest = smallest;
smallest = elements[i];
} else if (elements[i] < secondSmallest) {
secondSmallest = elements[i];
}
}
Here is TimeComlexity Linear O(N):
public static int secondSmallest(int[] arr) {
if(arr==null || arr.length < 2) {
throw new IllegalArgumentException("Input array too small");
}
//implement
int firstSmall = -1;
int secondSmall = -1;
//traverse to find 1st small integer on array
for (int i = 0; i<arr.length;i++)
if (firstSmall == -1 || arr[firstSmall]>arr[i])
firstSmall = i;
//traverse to array find 2 integer, and skip first small
for (int i = 0;i<arr.length;i++) {
if (i != firstSmall && (secondSmall == -1 || arr[secondSmall] > arr[i]))
secondSmall = i;
}
return arr[secondSmall];
}
int[] arr = { 4, 1, 2, 0, 6, 1, 2, 0 };
int smallest = Integer.MAX_VALUE;
int smaller = Integer.MAX_VALUE;
int i = 0;
if (arr.length > 2) {
for (i = 0; i < arr.length; i++) {
if (arr[i] < smallest) {
smaller = smallest;
smallest = arr[i];
} else if (arr[i] < smaller && arr[i] > smallest) {
smaller = arr[i];
}
}
System.out.println("Smallest number is " + smallest);
System.out.println("Smaller number is " + smaller);
} else {
System.out.println("Invalid array !");
}
}
You can do it in O(n) time. Below is the python code
def second_small(A):
if len(A)<2:
print 'Invalid Array...'
return
small = A[0]
second_small = [1]
if small > A[1]:
second_small,small = A[0],A[1]
for i in range(2,len(A)):
if A[i] < second_small and A[i]!=small:
if A[i] < small:
second_small = small
small = A[i]
else:
second_small = A[i]
print small, second_small
A = [12, 13, 1, 10, 34, 1]
second_small(A)
public static int findSecondSmallest(int[] elements) {
if (elements == null || elements.length < 2) {
throw new IllegalArgumentException();
}
int smallest = elements[0];
int secondSmallest = elements[0];
for (int i = 1; i < elements.length; i++) {
if (elements[i] < smallest) {
secondSmallest = smallest;
smallest = elements[i];
}
else if (elements[i] < secondSmallest) {
secondSmallest = elements[i];
}
}
return secondSmallest;
}
Simply, you can do this
int[] arr = new int[]{34, 45, 21, 12, 54, 67, 15};
Arrays.sort(arr);
System.out.println(arr[1]);
Try this one.
public static void main(String args[]){
int[] array = new int[]{10, 30, 15, 8, 20, 4};
int min, secondMin;
if (array[0] > array[1]){
min = array[1];
secondMin = array[0];
}
else{
min = array[0];
secondMin = array[1];
}
for (int i=2; i<array.length; i++){
if (array[i] < min){
secondMin = min;
min = array[i];
}
else if ((array[i] > min) && (array[i] < secondMin)){
secondMin = array[i];
}
}
System.out.println(secondMin);
}
I've used Sort function in javascript
function sumTwoSmallestNumbers(numbers){
numbers = numbers.sort(function(a, b){return a - b; });
return numbers[0] + numbers[1];
};
by providing a compareFunction for the sort functionality array elements are sorted according to the return value of the function.
How about this?
int[] result = Arrays.asList(-3, 4,-1,-2).stream()
.reduce(new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE},
(maxValues, x) -> {
if (x > maxValues[0]) {
maxValues[1] = maxValues[0]; //max becomes second max
maxValues[0] = x;
}
else if (x > maxValues[1]) maxValues[1] = x;
return maxValues;
}
, (x, y) -> x);
class A{
public static void main (String args[]){
int array[]= {-5, -4, 0, 2, 10, 3, -3};
int min;
int second_min;
if(array[0]<array[1]){
min=array[0];
second_min=array[1];
}else{
min=array[1];
second_min=array[0];
}
for(int i=2;i<array.length;i++){
if(second_min > array[i] && min > array[i]){
second_min=min;
min=array[i];
}else if(second_min > array[i] && min < array[i]){
min=min;
second_min=array[i];
}
}
System.out.println(min);
System.out.println(second_min);
}
}
Find the second minimum element of an array in Python, short and simple
def second_minimum(arr):
second = arr[1]
first = arr[0]
for n in arr:
if n < first:
first = n
if n > first and n < second :
second = n
return second
print(second_minimum([-2, 4, 5, -1, 2, 3, 0, -4, 1, 99, -6, -5, -19]))
public static void main(String[] args)
{
int[] elements = {-4 , 2 , 10 , -2, -3 };
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for (int i = 0; i < elements.length; i++)
{
if (smallest>elements[i])
smallest=elements[i];
}
for (int i = 0; i < elements.length; i++)
{
if (secondSmallest>elements[i] && elements[i]>smallest)
secondSmallest=elements[i];
}
System.out.println("The smallest element is: " + smallest + "\n"+ "The second smallest element is: " + secondSmallest);
}
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 small=n[0],ssmall=n[0];
// finding small and second small
for(int i=0;i<n.length;i++){
if(small>n[i]){
ssmall=small;
small=n[i];
}else if(ssmall>n[i])
ssmall=n[i];
}
// finding second small if first element itself small
if(small==n[0]){
ssmall=n[1];
for(int i=1;i<n.length;i++){
if(ssmall>n[i]){
ssmall=n[i];
}
}
}
System.out.println("Small "+ small+" sSmall "+ ssmall);
in.close();
}
public static void main(String[] args) {
int arr[] = {6,1,37,-4,12,46,5,64,21,2,-4,-3};
int lowest =arr[0];
int sec_lowest =arr[0];
for(int n : arr){
if (lowest > n)
{
sec_lowest = lowest;
lowest = n;
}
else if (sec_lowest > n && lowest != n)
sec_lowest = n;
}
System.out.println(lowest+" "+sec_lowest);
}
public class SecondSmallestNumberInArray
{
public static void main(String[] args)
{
int arr[] = { 99, 76, 47, 85, 929, 52, 48, 36, 66, 81, 9 };
int smallest = arr[0];
int secondSmallest = arr[0];
System.out.println("The given array is:");
boolean find = false;
boolean flag = true;
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
System.out.println("");
while (flag)
{
for (int i = 0; i < arr.length; i++)
{
if (arr[i] < smallest)
{
find = true;
secondSmallest = smallest;
smallest = arr[i];
} else if (arr[i] < secondSmallest) {
find = true;
secondSmallest = arr[i];
}
}
if (find) {
System.out.println("\nSecond Smallest number is Array : -> " + secondSmallest);
flag = false;
} else {
smallest = arr[1];
secondSmallest = arr[1];
}
}
}
}
**Output is**
D:\Java>java SecondSmallestNumberInArray
The given array is:
99 76 47 85 929 52 48 36 66 81 9
Second Smallest number is Array : -> 36
D:\Java>
public static int getSecondSmallest(int[] arr){
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for(int i=0;i<arr.length;i++){
if(smallest > arr[i]){
secondSmallest = smallest;
smallest = arr[i];
}else if (secondSmallest > arr[i] && arr[i] != smallest){
secondSmallest = arr[i];
}
System.out.println(i+" "+smallest+" "+secondSmallest);
}
return secondSmallest;
}
Just gave it a try with some of the test cases and it worked. Please check if it is correct!
Try this ...
First condition checks if both values are less than value in array.
Second condition if value is less than small than smallest=element[i]
else secondSmallest=elements[i]..
public static void main(String[] args)
{
int[] elements = {0 , 2 , 10 , 3, -3 };
int smallest = elements[0];
int secondSmallest = 0;
for (int i = 0; i < elements.Length; i++)
{
if (elements[i]<smallest || elements[i]<secondSmallest )
{
if (elements[i] < smallest )
{
secondSmallest = smallest ;
smallest = elements[i];
}
else
{
secondSmallest = elements[i];
}
}
}
System.out.println("The smallest element is: " + smallest + "\n"+ "The second smallest element is: " + secondSmallest);
}
Try this, program gives solution for both lowest value and second lowest value of array.
Initialize min and second_min with first element of array.Find out the min value and compare it with second_min value . If it (second_min) is greater than current element of array and min value then the second_min value replace with current element of array.
In case arr[]={2,6,12,15,11,0,3} like this , temp variable used to store previous second_min value.
public class Main
{
public static void main(String[] args) {
//test cases.
int arr[]={6,12,1,11,0};
//int arr[]={0,2,10,3,-3};
//int arr[]={0,0,10,3,-3};
//int arr[]={0,2 ,10, 3,-3};
//int arr[]={12,13,1,10,34,1};
//int arr[]={2,6,12,15,11,0,3};
//int arr[]={2,6,12,15,1,0,3};
//int arr[]={2,6,12,15};
//int arr[]={0,1};
//int arr[]={6,16};
//int arr[]={12};
//int arr[]={6,6,6,6,6,6};
int position_min=0;
int min=arr[0];int second_min=arr[0]; int temp=arr[0];
if(arr.length==1)
{
System.out.println("Lowest value is "+arr[0]+"\n Array length should be greater than 1. ");
}
else if(arr.length==2)
{
if(arr[0]>arr[1])
{
min=arr[1];
second_min=arr[0];
position_min=1;
}
else
{
min=arr[0];
second_min=arr[1];
position_min=0;
}
System.out.println("Lowest value is "+min+"\nSecond lowest value is "+second_min);
}
else
{
for( int i=1;i<arr.length;i++)
{
if(min>arr[i])
{
min=arr[i];
position_min=i;
}
}
System.out.println("Lowest value is "+min);
for(int i=1;i<arr.length;i++)
{
if(position_min==i)
{
}
else
{
if(second_min > min & second_min>arr[i])
{
temp=second_min;
second_min=arr[i];
}
else if(second_min == min )
{
second_min=arr[i];
}
}
}
if(second_min==min )
{
second_min=temp;
}
//just for message if in case all elements are same in array.
if(temp==min && second_min==min)
{
System.out.println("There is no Second lowest element in array.");
}
else{
System.out.println("\nSecond lowest value is "+second_min);
}
}
}
}
Here's a Swift version that runs in linear time. Basically, find the smallest number. Then assign the 2nd minimum number as the largest value. Then loop through through the array and find a number greater than the smallest one but also smaller than the 2nd smallest found so far.
func findSecondMinimumElementLinear(in nums: [Int]) -> Int? {
// If the size is less than 2, then returl nil.
guard nums.count > 1 else { return nil }
// First, convert it into a set to reduce duplicates.
let uniqueNums = Array(Set(nums))
// There is no point in sorting if all the elements were the same since it will only leave 1 element
// after the set removed duplicates.
if uniqueNums.count == 1 { return nil }
let min: Int = uniqueNums.min() ?? 0 // O(n)
var secondMinNum: Int = uniqueNums.max() ?? 0 // O(n)
// O(n)
for num in uniqueNums {
if num > min && num < secondMinNum {
secondMinNum = num
}
}
return secondMinNum
}
a straight forward solution in lambda
int[] first = {Integer.MAX_VALUE};
int rslt = IntStream.of( elements ).sorted().dropWhile( n -> {
boolean b = n == first[0] || first[0] == Integer.MAX_VALUE;
first[0] = n;
return( b );
} ).findFirst().orElse( Integer.MAX_VALUE );
the returned OptionalInt from findFirst() can be used to handle the special cases
for elements.length < 2 or elements containing only one value several times
here Integer.MAX_VALUE is returned, if there is no second smallest integer
Well, that should work for you:
function getSecondMin(array){
if(array.length < 2) return NaN;
let min = Math.min(array[0],array[1]);
let secondMin = Math.max(array[0],array[1])
for (let i = 2; i < array.length; i++) {
if(array[i]< min){
secondMin = min
min = array[i]
}
else if(array[i] < secondMin){
secondMin = array[i]
}
}
return secondMin;
}
const secondMin = getSecondMin([1,4,3,100,2])
console.log(secondMin || "invalid array length");

Finding the second smallest integer in array

We are required in our assignment to find the second smallest integer in one array recursively. However, for the sake of understanding the subject more, I want to do it iteratively first (with the help of this website) and recursively on my own.
Unfortunately, doing it iteratively is quite confusing. I understand that the solution is simple but i can't wrap my head around it.
Below is my code, so far:
public static void main(String[] args)
{
int[] elements = {0 , 2 , 10 , 3, -3 };
int smallest = 0;
int secondSmallest = 0;
for (int i = 0; i < elements.length; i++)
{
for (int j = 0; j < elements.length; j++)
{
if (elements[i] < smallest)
{
smallest = elements[i];
if (elements[j] < secondSmallest)
{
secondSmallest = elements[j];
}
}
}
}
System.out.println("The smallest element is: " + smallest + "\n"+ "The second smallest element is: " + secondSmallest);
}
This works for a few numbers, but not all. The numbers change around because the inner if condition isn't as efficient as the outer if condition.
Array rearrangements are forbidden.
Try this one. Second condition is used to catch an event when the smallest number is the first
int[] elements = {-5, -4, 0, 2, 10, 3, -3};
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for (int i = 0; i < elements.length; i++) {
if(elements[i]==smallest){
secondSmallest=smallest;
} else if (elements[i] < smallest) {
secondSmallest = smallest;
smallest = elements[i];
} else if (elements[i] < secondSmallest) {
secondSmallest = elements[i];
}
}
UPD by #Axel
int[] elements = {-5, -4, 0, 2, 10, 3, -3};
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for (int i = 0; i < elements.length; i++) {
if (elements[i] < smallest) {
secondSmallest = smallest;
smallest = elements[i];
} else if (elements[i] < secondSmallest) {
secondSmallest = elements[i];
}
}
Here is TimeComlexity Linear O(N):
public static int secondSmallest(int[] arr) {
if(arr==null || arr.length < 2) {
throw new IllegalArgumentException("Input array too small");
}
//implement
int firstSmall = -1;
int secondSmall = -1;
//traverse to find 1st small integer on array
for (int i = 0; i<arr.length;i++)
if (firstSmall == -1 || arr[firstSmall]>arr[i])
firstSmall = i;
//traverse to array find 2 integer, and skip first small
for (int i = 0;i<arr.length;i++) {
if (i != firstSmall && (secondSmall == -1 || arr[secondSmall] > arr[i]))
secondSmall = i;
}
return arr[secondSmall];
}
int[] arr = { 4, 1, 2, 0, 6, 1, 2, 0 };
int smallest = Integer.MAX_VALUE;
int smaller = Integer.MAX_VALUE;
int i = 0;
if (arr.length > 2) {
for (i = 0; i < arr.length; i++) {
if (arr[i] < smallest) {
smaller = smallest;
smallest = arr[i];
} else if (arr[i] < smaller && arr[i] > smallest) {
smaller = arr[i];
}
}
System.out.println("Smallest number is " + smallest);
System.out.println("Smaller number is " + smaller);
} else {
System.out.println("Invalid array !");
}
}
You can do it in O(n) time. Below is the python code
def second_small(A):
if len(A)<2:
print 'Invalid Array...'
return
small = A[0]
second_small = [1]
if small > A[1]:
second_small,small = A[0],A[1]
for i in range(2,len(A)):
if A[i] < second_small and A[i]!=small:
if A[i] < small:
second_small = small
small = A[i]
else:
second_small = A[i]
print small, second_small
A = [12, 13, 1, 10, 34, 1]
second_small(A)
public static int findSecondSmallest(int[] elements) {
if (elements == null || elements.length < 2) {
throw new IllegalArgumentException();
}
int smallest = elements[0];
int secondSmallest = elements[0];
for (int i = 1; i < elements.length; i++) {
if (elements[i] < smallest) {
secondSmallest = smallest;
smallest = elements[i];
}
else if (elements[i] < secondSmallest) {
secondSmallest = elements[i];
}
}
return secondSmallest;
}
Simply, you can do this
int[] arr = new int[]{34, 45, 21, 12, 54, 67, 15};
Arrays.sort(arr);
System.out.println(arr[1]);
Try this one.
public static void main(String args[]){
int[] array = new int[]{10, 30, 15, 8, 20, 4};
int min, secondMin;
if (array[0] > array[1]){
min = array[1];
secondMin = array[0];
}
else{
min = array[0];
secondMin = array[1];
}
for (int i=2; i<array.length; i++){
if (array[i] < min){
secondMin = min;
min = array[i];
}
else if ((array[i] > min) && (array[i] < secondMin)){
secondMin = array[i];
}
}
System.out.println(secondMin);
}
I've used Sort function in javascript
function sumTwoSmallestNumbers(numbers){
numbers = numbers.sort(function(a, b){return a - b; });
return numbers[0] + numbers[1];
};
by providing a compareFunction for the sort functionality array elements are sorted according to the return value of the function.
How about this?
int[] result = Arrays.asList(-3, 4,-1,-2).stream()
.reduce(new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE},
(maxValues, x) -> {
if (x > maxValues[0]) {
maxValues[1] = maxValues[0]; //max becomes second max
maxValues[0] = x;
}
else if (x > maxValues[1]) maxValues[1] = x;
return maxValues;
}
, (x, y) -> x);
class A{
public static void main (String args[]){
int array[]= {-5, -4, 0, 2, 10, 3, -3};
int min;
int second_min;
if(array[0]<array[1]){
min=array[0];
second_min=array[1];
}else{
min=array[1];
second_min=array[0];
}
for(int i=2;i<array.length;i++){
if(second_min > array[i] && min > array[i]){
second_min=min;
min=array[i];
}else if(second_min > array[i] && min < array[i]){
min=min;
second_min=array[i];
}
}
System.out.println(min);
System.out.println(second_min);
}
}
Find the second minimum element of an array in Python, short and simple
def second_minimum(arr):
second = arr[1]
first = arr[0]
for n in arr:
if n < first:
first = n
if n > first and n < second :
second = n
return second
print(second_minimum([-2, 4, 5, -1, 2, 3, 0, -4, 1, 99, -6, -5, -19]))
public static void main(String[] args)
{
int[] elements = {-4 , 2 , 10 , -2, -3 };
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for (int i = 0; i < elements.length; i++)
{
if (smallest>elements[i])
smallest=elements[i];
}
for (int i = 0; i < elements.length; i++)
{
if (secondSmallest>elements[i] && elements[i]>smallest)
secondSmallest=elements[i];
}
System.out.println("The smallest element is: " + smallest + "\n"+ "The second smallest element is: " + secondSmallest);
}
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 small=n[0],ssmall=n[0];
// finding small and second small
for(int i=0;i<n.length;i++){
if(small>n[i]){
ssmall=small;
small=n[i];
}else if(ssmall>n[i])
ssmall=n[i];
}
// finding second small if first element itself small
if(small==n[0]){
ssmall=n[1];
for(int i=1;i<n.length;i++){
if(ssmall>n[i]){
ssmall=n[i];
}
}
}
System.out.println("Small "+ small+" sSmall "+ ssmall);
in.close();
}
public static void main(String[] args) {
int arr[] = {6,1,37,-4,12,46,5,64,21,2,-4,-3};
int lowest =arr[0];
int sec_lowest =arr[0];
for(int n : arr){
if (lowest > n)
{
sec_lowest = lowest;
lowest = n;
}
else if (sec_lowest > n && lowest != n)
sec_lowest = n;
}
System.out.println(lowest+" "+sec_lowest);
}
public class SecondSmallestNumberInArray
{
public static void main(String[] args)
{
int arr[] = { 99, 76, 47, 85, 929, 52, 48, 36, 66, 81, 9 };
int smallest = arr[0];
int secondSmallest = arr[0];
System.out.println("The given array is:");
boolean find = false;
boolean flag = true;
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
System.out.println("");
while (flag)
{
for (int i = 0; i < arr.length; i++)
{
if (arr[i] < smallest)
{
find = true;
secondSmallest = smallest;
smallest = arr[i];
} else if (arr[i] < secondSmallest) {
find = true;
secondSmallest = arr[i];
}
}
if (find) {
System.out.println("\nSecond Smallest number is Array : -> " + secondSmallest);
flag = false;
} else {
smallest = arr[1];
secondSmallest = arr[1];
}
}
}
}
**Output is**
D:\Java>java SecondSmallestNumberInArray
The given array is:
99 76 47 85 929 52 48 36 66 81 9
Second Smallest number is Array : -> 36
D:\Java>
public static int getSecondSmallest(int[] arr){
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for(int i=0;i<arr.length;i++){
if(smallest > arr[i]){
secondSmallest = smallest;
smallest = arr[i];
}else if (secondSmallest > arr[i] && arr[i] != smallest){
secondSmallest = arr[i];
}
System.out.println(i+" "+smallest+" "+secondSmallest);
}
return secondSmallest;
}
Just gave it a try with some of the test cases and it worked. Please check if it is correct!
Try this ...
First condition checks if both values are less than value in array.
Second condition if value is less than small than smallest=element[i]
else secondSmallest=elements[i]..
public static void main(String[] args)
{
int[] elements = {0 , 2 , 10 , 3, -3 };
int smallest = elements[0];
int secondSmallest = 0;
for (int i = 0; i < elements.Length; i++)
{
if (elements[i]<smallest || elements[i]<secondSmallest )
{
if (elements[i] < smallest )
{
secondSmallest = smallest ;
smallest = elements[i];
}
else
{
secondSmallest = elements[i];
}
}
}
System.out.println("The smallest element is: " + smallest + "\n"+ "The second smallest element is: " + secondSmallest);
}
Try this, program gives solution for both lowest value and second lowest value of array.
Initialize min and second_min with first element of array.Find out the min value and compare it with second_min value . If it (second_min) is greater than current element of array and min value then the second_min value replace with current element of array.
In case arr[]={2,6,12,15,11,0,3} like this , temp variable used to store previous second_min value.
public class Main
{
public static void main(String[] args) {
//test cases.
int arr[]={6,12,1,11,0};
//int arr[]={0,2,10,3,-3};
//int arr[]={0,0,10,3,-3};
//int arr[]={0,2 ,10, 3,-3};
//int arr[]={12,13,1,10,34,1};
//int arr[]={2,6,12,15,11,0,3};
//int arr[]={2,6,12,15,1,0,3};
//int arr[]={2,6,12,15};
//int arr[]={0,1};
//int arr[]={6,16};
//int arr[]={12};
//int arr[]={6,6,6,6,6,6};
int position_min=0;
int min=arr[0];int second_min=arr[0]; int temp=arr[0];
if(arr.length==1)
{
System.out.println("Lowest value is "+arr[0]+"\n Array length should be greater than 1. ");
}
else if(arr.length==2)
{
if(arr[0]>arr[1])
{
min=arr[1];
second_min=arr[0];
position_min=1;
}
else
{
min=arr[0];
second_min=arr[1];
position_min=0;
}
System.out.println("Lowest value is "+min+"\nSecond lowest value is "+second_min);
}
else
{
for( int i=1;i<arr.length;i++)
{
if(min>arr[i])
{
min=arr[i];
position_min=i;
}
}
System.out.println("Lowest value is "+min);
for(int i=1;i<arr.length;i++)
{
if(position_min==i)
{
}
else
{
if(second_min > min & second_min>arr[i])
{
temp=second_min;
second_min=arr[i];
}
else if(second_min == min )
{
second_min=arr[i];
}
}
}
if(second_min==min )
{
second_min=temp;
}
//just for message if in case all elements are same in array.
if(temp==min && second_min==min)
{
System.out.println("There is no Second lowest element in array.");
}
else{
System.out.println("\nSecond lowest value is "+second_min);
}
}
}
}
Here's a Swift version that runs in linear time. Basically, find the smallest number. Then assign the 2nd minimum number as the largest value. Then loop through through the array and find a number greater than the smallest one but also smaller than the 2nd smallest found so far.
func findSecondMinimumElementLinear(in nums: [Int]) -> Int? {
// If the size is less than 2, then returl nil.
guard nums.count > 1 else { return nil }
// First, convert it into a set to reduce duplicates.
let uniqueNums = Array(Set(nums))
// There is no point in sorting if all the elements were the same since it will only leave 1 element
// after the set removed duplicates.
if uniqueNums.count == 1 { return nil }
let min: Int = uniqueNums.min() ?? 0 // O(n)
var secondMinNum: Int = uniqueNums.max() ?? 0 // O(n)
// O(n)
for num in uniqueNums {
if num > min && num < secondMinNum {
secondMinNum = num
}
}
return secondMinNum
}
a straight forward solution in lambda
int[] first = {Integer.MAX_VALUE};
int rslt = IntStream.of( elements ).sorted().dropWhile( n -> {
boolean b = n == first[0] || first[0] == Integer.MAX_VALUE;
first[0] = n;
return( b );
} ).findFirst().orElse( Integer.MAX_VALUE );
the returned OptionalInt from findFirst() can be used to handle the special cases
for elements.length < 2 or elements containing only one value several times
here Integer.MAX_VALUE is returned, if there is no second smallest integer
Well, that should work for you:
function getSecondMin(array){
if(array.length < 2) return NaN;
let min = Math.min(array[0],array[1]);
let secondMin = Math.max(array[0],array[1])
for (let i = 2; i < array.length; i++) {
if(array[i]< min){
secondMin = min
min = array[i]
}
else if(array[i] < secondMin){
secondMin = array[i]
}
}
return secondMin;
}
const secondMin = getSecondMin([1,4,3,100,2])
console.log(secondMin || "invalid array length");

Find smallest integer value in array list in Java without Arrays.sort

How can I find the smallest value in a int array without changing the array order?
code snippet:
int[] tenIntArray = new int [10];
int i, userIn;
Scanner KyBdIn = new Scanner(System.in);
System.out.println("Please enter 10 integer numbers ");
for(i = 0; i < tenIntArray.length; i++){
System.out.println("Please enter integer " + i);
userIn = KyBdIn.nextInt();
tenIntArray[i] = userIn;
}
I am not sure how I can find the smallest array value in the tenIntArray and display the position
For example the array holds - [50, 8, 2, 3, 1, 9, 8, 7 ,54, 10]
The output should say "The smallest value is 1 at position 5 in array"
This figure should be helpful :
Then to answer your question, what would you do on paper ?
Create and initialize the min value at tenIntArray[0]
Create a variable to hold the index of the min value in the array and initialize it to 0 (because we said in 1. to initialize the min at tenIntArray[0])
Loop through the elements of your array
If you find an element inferior than the current min, update the minimum value with this element and update the index with the corresponding index of this element
You're done
Writing the algorithm should be straightforward now.
Try this:
//Let arr be your array of integers
if (arr.length == 0)
return;
int small = arr[0];
int index = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] < small) {
small = arr[i];
index = i;
}
}
Using Java 8 Streams you can create a Binary operator which compares two integers and returns smallest among them.
Let arr is your array
int[] arr = new int[]{54,234,1,45,14,54};
int small = Arrays.stream(arr).reduce((x, y) -> x < y ? x : y).getAsInt();
The method I am proposing will find both min and max.
public static void main(String[] args) {
findMinMax(new int[] {10,40,50,20,69,37});
}
public static void findMinMax(int[] array) {
if (array == null || array.length < 1)
return;
int min = array[0];
int max = array[0];
for (int i = 1; i <= array.length - 1; i++) {
if (max < array[i]) {
max = array[i];
}
if (min > array[i]) {
min = array[i];
}
}
System.out.println("min: " + min + "\nmax: " + max);
}
Obviously this is not going to one of the most optimized solution but it will work for you. It uses simple comparison to track min and max values. Output is:
min: 10
max: 69
int[] input = {12,9,33,14,5,4};
int max = 0;
int index = 0;
int indexOne = 0;
int min = input[0];
for(int i = 0;i<input.length;i++)
{
if(max<input[i])
{
max = input[i];
indexOne = i;
}
if(min>input[i])
{
min = input[i];
index = i;
}
}
System.out.println(max);
System.out.println(indexOne);
System.out.println(min);
System.out.println(index);
Here is the function
public int getIndexOfMin(ArrayList<Integer> arr){
int minVal = arr.get(0); // take first as minVal
int indexOfMin = -1; //returns -1 if all elements are equal
for (int i = 0; i < arr.size(); i++) {
//if current is less then minVal
if(arr.get(i) < minVal ){
minVal = arr.get(i); // put it in minVal
indexOfMin = i; // put index of current min
}
}
return indexOfMin;
}
the first index of a array is zero. not one.
for(i = 0; i < tenIntArray.length; i++)
so correct this.
the code that you asked is :
int small = Integer.MAX_VALUE;
int i = 0;
int index = 0;
for(int j : tenIntArray){
if(j < small){
small = j;
i++;
index = i;
}
}
System.out.print("The smallest value is"+small+"at position"+ index +"in array");

find second and third maximum element array java

I have to find 1st, 2nd, and 3rd largest array. I know I could simply sort it and return array[0], array[1], array[3]. But the problem is, i need the index, not the value.
For example if i have float[] listx={8.0, 3.0, 4.0, 5.0, 9.0} it should return 4, 0, and 3.
Here's the code I have but it doesn't work:
//declaration max1-3
public void maxar (float[] listx){
float maxel1=0;
float maxel2=0;
float maxel3=0;
for (int i=0; i<listx.length; i++){
if(maxel1<listx[i])
{maxel1=listx[i];
max1=i;
}
}
listx[max1]=0; //to exclude this one in nextsearch
for (int j=0; j<listx.length; j++){
if(listx[j]>maxel2)
{maxel2=listx[j];
max2=j;
}
}
listx[max2]=0;
for (int k=0; k<listx.length; k++){
if(listx[k]>maxel3)
{maxel3=listx[k];
max3=k;
}
}
}
I get max1 right but after that all the elements turns to 0. hence max2 and max3 become 0. Please suggest me what is wrong with this solution. Thank you.
You can find the three elements using a single loop, and you don't need to modify the array.
When you come across a new largest element, you need to shift the previous largest and the previous second-largest down by one position.
Similarly, when you find a new second-largest element, you need to shift maxel2 into maxel3.
Instead of using the three variables, you might want to employ an array. This will enable you to streamline the logic, and make it easy to generalize to k largest elements.
Make 3 passes over array: on first pass find value and 1st index of maximum element M1, on second pass find value and 1st index of maximum element M2 which is lesser than M1 and on third pass find value/1st index M3 < M2.
Try this code it will work :)
public class Array
{
public void getMax( double ar[] )
{
double max1 = ar[0]; // Assume the first
double max2 = ar[0]; // element in the array
double max3 = ar[0]; // is the maximum element.
int ZERO = 0;
// Variable to store inside it the index of the max value to set it to zero.
for( int i = 0; i < ar.length; i++ )
{
if( ar[i] >= max1)
{
max1 = ar[i];
ZERO = i;
}
}
ar[ZERO] = 0; // Set the index contains the 1st max to ZERO.
for( int j = 0; j < ar.length; j++ )
{
if( ar[j] >= max2 )
{
max2 = ar[j];
ZERO = j;
}
}
ar[ZERO] = 0; // Set the index contains the 2st max to ZERO.
for( int k = 0; k < ar.length; k++ )
{
if( ar[k] >= max3 )
{
max3 = ar[k];
ZERO = k;
}
}
System.out.println("1st max:" + max1 + ", 2nd: " +max2 + ",3rd: "+ max3);
}
public static void main(String[] args)
{
// Creating an object from the class Array to be able to use its methods.
Array array = new Array();
// Creating an array of type double.
double a[] = {2.2, 3.4, 5.5, 5.5, 6.6, 5.6};
array.getMax( a ); // Calling the method that'll find the 1st max, 2nd max, and and 3rd max.
}
}
I suggest making a single pass instead of three for optimization. The code below works for me. Note that the code does not assert that listx has at least 3 elements. It is up to you to decide what should happen in case it contains only 2 elements or less.
What I like about this code is that it only does one pass over the array, which in its best case would have faster running time compared to doing three passes, with a factor proportionate to the number of elements in listx.
Assume i1, i2 and i3 store the indices of the three greatest elements in listx, and i0 is one of i1, i2 and i3 that points to the smallest element. In the beginning, i1 = i2 = i3 because we haven't found the largest elements yet. So let i0 = i1. If we find a new index j such that that listx[j] > listx[i0], we set i0 = j, replacing that old index with an index that leads to a greater element. Then we find the index among i1, i2 and i3 that now leads to the smallest element of out the three, so that we can safely discard that one in case a new large element comes along.
Note: This code is in C, so translate it to Java if you want to use it. I made sure to use similar syntax to make that easier. (I wrote it in C because I lacked a Java testing environment.)
void maxar(float listx[], int count) {
int maxidx[3] = {0};
/* The index of the 3rd greatest element
* in listx.
*/
int max_3rd = 0;
for (int i = 0; i < count; i++) {
if (listx[maxidx[max_3rd]] < listx[i]) {
/* Exchange 3rd greatest element
* with new greater element.
*/
maxidx[max_3rd] = i;
/* Find index of smallest maximum. */
for (int j = (max_3rd + 1) % 3; j != max_3rd; j = (j + 1) % 3) {
if (listx[maxidx[j]] < listx[maxidx[max_3rd]]) {
max_3rd = j;
}
}
}
}
/* `maxidx' now contains the indices of
* the 3 greatest values in `listx'.
*/
printf("3 maximum elements (unordered):\n");
for (int i = 0; i < 3; i++) {
printf("index: %2d, element: %f\n", maxidx[i], listx[maxidx[i]]);
}
}
public class ArrayExample {
public static void main(String[] args) {
int secondlargest = 0;
int thirdLargest=0;
int largest = 0;
int arr[] = {5,4,3,8,12,95,14,376,37,2,73};
for (int i = 0; i < arr.length; i++) {
if (largest < arr[i]) {
secondlargest = largest;
largest = arr[i];
}
if (secondlargest < arr[i] && largest != arr[i])
secondlargest = arr[i];
if(thirdLargest<arr[i] && secondlargest!=arr[i] && largest!=arr[i] && thirdLargest<largest && thirdLargest<secondlargest)
thirdLargest =arr[i];
}
System.out.println("Largest number is: " + largest);
System.out.println("Second Largest number is: " + secondlargest);
System.out.println("third Largest number is: " + thirdLargest);
}
}
def third_mar_array(arr):
max1=0
max2=0
max3=0
for i in range(0,len(arr)-1):
if max1<arr[i]:
max1=arr[i]
max_in1=i
arr[max_in1]=0
for j in range(0,len(arr)-1):
if max2<arr[j]:
max2=arr[j]
max_in2=j
arr[max_in2]=0
for k in range(0,len(arr)-1):
if max3<arr[k]:
max3=arr[k]
max_in3=k
#arr[max_in3]=0
return max3
n=[5,6,7,3,2,1]
f=first_array(n)
print f
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testcase = sc.nextInt();
while (testcase-- > 0) {
int sizeOfArray = sc.nextInt();
int[] arr = new int[sizeOfArray];
for (int i = 0; i < sizeOfArray; i++) {
arr[i] = sc.nextInt();
}
int max1, max2, max3;
max1 = 0;
max2 = 0;
max3 = 0;
for (int i = 0; i < sizeOfArray; i++) {
if (arr[i] > max1) {
max3 = max2;
max2 = max1;
max1 = arr[i];
}
else if (arr[i] > max2) {
max3 = max2;
max2 = arr[i];
}
else if (arr[i] > max3) {
max3 = arr[i];
}
}
System.out.println(max1 + " " + max2 + " " + max3);
}
}
}

Categories