Issue with java array not identifying maximum number - java

This code is entirely completed. I'm having an issue where the maximum number is being selected and printed as the number right before the maximum. I can't seem to figure out how to make the program print out the actual maximum. For clarification, I'm not looking for an answer to my homework as the code is 99.9% done, I just need assistance on this one issue.
Here's the code:
package Zivkovic7;
import java.util.Arrays;
import java.util.Random;
public class Test {
private static Random rand = new Random();
public static void main(String[] args) {
int[] randomEight = new int[8];
for (int i = 0; i < 8; i++) {
//Get a random number between 50 and 100
randomEight[i] = rand.nextInt(51) + 50;
}
int[] extremeValues = sortArray(randomEight);
System.out.println("The lowest element is " + extremeValues[0]);
System.out.println("The highest element is " + extremeValues[1]);
int sum = 0;
int oddCount = 0;
int evenCount = 0;
System.out.println("\nHere is the array: ");
for (int i = 0; i < randomEight.length; i++) {
System.out.print(randomEight[i] + " ");
if (randomEight[i] % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
sum += randomEight[i];
}
System.out.println("\nEvens: " + evenCount);
System.out.println("\nOdds: " + oddCount);
System.out.println("\nSum of all elements : " + sum);
}
public static int[] sortArray(int[] input) {
int extremeVal[] = new int[2];
extremeVal[0] = input[0]; /* Minimum */
extremeVal[1] = input[1]; /* Maximum */
/*
* Bubble Sort Algorithm
* */
int n = input.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (input[j] > input[j + 1]) {
int temp = input[j];
input[j] = input[j + 1];
input[j + 1] = temp;
}
}
/* Finding minimum */
if (extremeVal[0] > input[i]) {
extremeVal[0] = input[i];
}
/* Finding maximum */
if (extremeVal[1] < input[i]) {
extremeVal[1] = input[i];
}
}
return extremeVal;
}
}
Sorry if anything looks wonky, this is my first time posting to stack overflow. Also, if any more information is needed, i can promptly provide.

You don't need to capture the min and max at each iteration. Just wait the end of sorting.
You failed because the maximum was always the n-2 (the second maximum)
This might help. Change the end of your code with these lines.
// /* Finding minimum */
// if (extremeVal[0] > input[i]) {
// extremeVal[0] = input[i];
// }
// /* Finding maximum */
// if (extremeVal[1] < input[i]) {
// extremeVal[1] = input[i];
// }
}
extremeVal[0] = input[0];
extremeVal[1] = input[n-1];
return extremeVal;

Related

Creating an array from the values of another array?

New to java and I am working on a RLE encoder. A method I am working on right now requires to convert an array of example:
{13,13,13,4,4,4,4,4,4}
to
{3,13,6,4}.
It checks the numbers that appear in consecutive order and then prints that into index[i], then prints the actual number value in index[i+1].
My current issue is that if a number is repeated more than 15 times, I have to start a new "run". So {13,13,13,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,} (there are 20 4's in succession here) will print {3,13,15,4,5,4}. My code currently prints {3,15,20,4}.
import java.util.Arrays;
public class testing {
public static void main(String[] args) {
byte [] flatdata = {15,15,15,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4};
int count = 1;
for (int i = 0; i < flatdata.length - 1; i++) {
if (flatdata[i] != flatdata[i + 1]) {
count++; }
}
byte numLength = 1;
byte indexNum = 0;
int newArraySize = count * 2;
byte[] newArray = new byte[newArraySize];
byte[] arrayWithTotalIndexes = new byte[newArraySize];
int i;
for (i = 0; i < flatdata.length - 1; i++) {
if (flatdata[i] != flatdata[i + 1]) {
newArray[indexNum] = numLength;
newArray[indexNum + 1] = flatdata[i];
indexNum = (byte) (indexNum + 2);
numLength = 1;
} else {
numLength++;
}
}
if (flatdata[i - 1] == flatdata[i]) {
newArray[indexNum] = numLength;
newArray[indexNum + 1] = flatdata[i];
} else {
newArray[indexNum] = numLength;
newArray[indexNum + 1] = flatdata[i];
}
System.out.println(Arrays.toString(flatdata));
System.out.println(Arrays.toString(newArray));
System.out.println("countRuns: " + count);
System.out.println(Arrays.toString(arrayWithTotalIndexes));
byte[] desiredArray = {3,15,15,4,5,4};
System.out.println("Desired Array: " + Arrays.toString(desiredArray));
}
I know my first step has to be to adjust the size of the new array to include the extra entries of the array.
public static void main(String [] args){
byte [] arr = {15,15,15,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,};
for (int i = 0; i < arr.length; i++) {
int count1 = 0;
for (int j = 0; j < arr.length; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
if (count1 > 15) {
System.out.println("true");
break;
}
System.out.println("false");
}
}
I thought about running a separate loop to check if a number is repeated more than 15 times to change the size of the new array but it has been to no avail.
Here is a link to a previous question I asked regarding the same method in case it makes things more clear.
Creating an array from another array?
Would appreciate any tips or ideas on how to tackle this.
Expand the test for starting a new result pair by changing:
if (flatdata[i] != flatdata[i + 1])
to:
if (flatdata[i] != flatdata[i + 1] || numLength == 15)

Sieve of Eratosthenes will not sieve Prime Numbers

For an assignment I am doing for one of my classes, we have to implement a Sieve of Eratosthenes. I have tried seven times to get a code that works and have tried incorporating numerous solutions I've researched. I finally have one that will output numbers. Unfortunately, it prints both composite and prime numbers, and doesn't print 2.
My code is as follows:
public class EratosthenesSieveAttempt6 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int limit;
System.out.print("Please enter the highest number to check "
+ "(number must be greater than 2): ");
limit = keyboard.nextInt();
while (limit <= 2){
System.out.println("Error - number must be greater than 2.");
System.out.println("Please enter the highest number to check: ");
limit = keyboard.nextInt();
}
boolean[] numbers = new boolean[limit + 1];
int newPrime = 2;
for(int i = 0; i < limit + 1; i++){
numbers[i] = true;
}
for(int j = 1; j < limit + 1; j++) {
if (j % 2 == 0) {
numbers[j] = false;
}
for(int k = j + 1; k < limit + 1; k++) {
if(numbers[k] == true){
j = k;
System.out.println(k);
}
}
}
}
}
I'm suspecting that there is a problem with my loops. I fixed the i and j variables for my first two loops so that it would print out from 2 onward, the problem seems to be that it's not marking the composite numbers as false after I've initialized the array to true.
Thank you in advance for your help.
Here's an implementation of the Sieve of Eratosthenes I wrote the other day:
import java.util.BitSet;
public static BitSet composite(int max) {
BitSet composite = new BitSet(max);
max = composite.size();
for (int i = 4; i < max; i += 2) composite.set(i, true);
for (int i = 9; i < max; i += 6) composite.set(i, true);
int p = 5;
while (p*p < max) {
if (!composite.get(p)) {
for (int i = p*p; i < max; i += p*2) composite.set(i, true);
}
p += 2;
if (p*p >= max) break;
if (!composite.get(p)) {
for (int i = p*p; i < max; i += p*2) composite.set(i, true);
}
p += 4;
}
return composite;
}
Notes:
BitSet allocates 64-bit words, so the size may be larger than you requested (for example, if you ask it to go up to 1000, it will go up to 1024; that's the reason for max = composite.size() near the top)
Gets the 2's, 3's out of the way explicitly, and then
Relies on the fact that all primes larger than 3 are congruent to either 1 or 5 mod 6; this is the reason the final loop alternates between adding 2 and 4
It returns a BitSet that tells you which numbers are composite. One way to extract just the primes from it would be:
public static int[] primes(BitSet composite) {
int size = composite.size() - 2 - composite.cardinality();
int[] primes = new int[size];
int index = 0;
for (int i = 2; i < composite.size(); i++) {
if (!composite.get(i)) primes[index++] = i;
}
return primes;
}

Smallest sum of triplet products where the middle element is removed using Dynamic Programming

I have given a sequence of N numbers (4 ≤ N ≤ 150). One index i (0 < i < N) is picked and multiplied with the left and the right number, in other words with i-1 and i+1. Then the i-th number is removed. This is done until the sequence has only two numbers left over. The goal is to find the smallest sum of these products which obviously depends on the order in which the indices are picked.
E.g. for the sequence 44, 45, 5, 39, 15, 22, 10 the smallest sum would be 17775
using the indices in the following order: 1->3->4->5->2 which is the sum:
44*45*5 + 5*39*15 + 5*15*22 + 5*22*10 + 44*5*10 = 9900 + 2925 + 1650 + 1100 + 2200 = 17775
I have found a solution using a recursive function:
public static int smallestSum(List<Integer> values) {
if (values.size() == 3)
return values.get(0) * values.get(1) * values.get(2);
else {
int ret = Integer.MAX_VALUE;
for (int i = 1; i < values.size() - 1; i++) {
List<Integer> copy = new ArrayList<Integer>(values);
copy.remove(i);
int val = smallestSum(copy) + values.get(i - 1) * values.get(i) * values.get(i + 1);
if (val < ret) ret = val;
}
return ret;
}
}
However, this solution is only feasible for small N but not for a bigger amount of numbers. What I am looking for is a way to do this using an iterative Dynamic Programming approach.
The optimal substructure needed for a DP is that, given the identity of the last element removed, the elimination strategy for the elements to the left is independent of the elimination strategy for the elements to the right. Here's a new recursive function (smallestSumA, together with the version from the question and a test harness comparing the two) incorporating this observation:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Foo {
public static void main(String[] args) {
Random r = new Random();
for (int i = 0; i < 10000; i++) {
List<Integer> values = new ArrayList<Integer>();
for (int n = 3 + r.nextInt(8); n > 0; n--) {
values.add(r.nextInt(100));
}
int a = smallestSumA(values, 0, values.size() - 1);
int q = smallestSumQ(values);
if (q != a) {
System.err.println("oops");
System.err.println(q);
System.err.println(a);
System.err.println(values);
}
}
}
public static int smallestSumA(List<Integer> values, int first, int last) {
if (first + 2 > last)
return 0;
int ret = Integer.MAX_VALUE;
for (int i = first + 1; i <= last - 1; i++) {
int val = (smallestSumA(values, first, i)
+ values.get(first) * values.get(i) * values.get(last) + smallestSumA(values, i, last));
if (val < ret)
ret = val;
}
return ret;
}
public static int smallestSumQ(List<Integer> values) {
if (values.size() == 3)
return values.get(0) * values.get(1) * values.get(2);
else {
int ret = Integer.MAX_VALUE;
for (int i = 1; i < values.size() - 1; i++) {
List<Integer> copy = new ArrayList<Integer>(values);
copy.remove(i);
int val = smallestSumQ(copy) + values.get(i - 1) * values.get(i) * values.get(i + 1);
if (val < ret)
ret = val;
}
return ret;
}
}
}
Invoke as smallestSum(values, 0, values.size() - 1).
To get the DP, observe that there are only N choose 2 different settings for first and last, and memoize. The running time is O(N^3).
If anyone is interested in a DP solution, based on David Eisenstat's recursive solution, here is an iterative one using DP (for many big numbers it's useful to replace int's with long's):
public static int smallestSum(List<Integer> values) {
int[][] table = new int[values.size()][values.size()];
for (int i = 2; i < values.size(); i++) {
for (int j = 0; j + i < values.size(); j++) {
int ret = Integer.MAX_VALUE;
for (int k = j + 1; k <= j + i - 1; k++) {
int val = table[j][k] + values.get(j) * values.get(k) * values.get(j + i) + table[k][j + i];
if (val < ret) ret = val;
}
table[j][j + i] = ret;
}
}
return table[0][values.size() - 1];
}

Maximum Single Sell Profit algorithm (Java)

I am working on creating an algorithm to maximize profit from a .txt file where each line is the price of a certain stock on a day (Starting with day 0).
The output of my program should be "[day you should buy the stock, day you should sell the stock, profit made]".
For example:
Text file:
12, 45, 3, 15, 60, 23, 4
The output should be [2, 4, 57].
My code returns the actual VALUES and not the index of those values.
My output: [3, 60, 57].
I am a beginner, and I cannot seem to find out what to do to produce the correct output! Help would be very much appreciated!
(Trade is a separate class that returns (in, out, profit)).
[EDIT]: I am supposed to do this recursively, and make sure the the overall time cost of the solution is O(n log n)!
Here is my code:
(Apologies if it is messy/things are in it that aren't needed! :) )
import java.util.*;
import java.lang.Math;
import java.io.*;
public class Test_BestTrading
{
public static void main(String[] args) throws Exception
{
//open file
String fileName = args[0];
File inFile = new File(fileName);
Scanner fin = new Scanner(inFile);
int count = 0;
//find out length of array
while(fin.hasNext())
{
fin.nextLine();
count++;
}
fin.close();
int[]p = new int[count];
fin = new Scanner(inFile);
//read numbers into array
for(int i =0; i < count; i++)
p[i] = Integer.parseInt(fin.nextLine());
Trade trade = BestTrade(p, 0, p.length-1);
System.out.println("[" + trade.in + ", " + trade.out + ", " + trade.profit + "]");
}
public static Trade BestTrade(int[] p, int in, int out)
{
if (p.length <= 1)
return new Trade(in, out, out-in);
//Create two arrays - one is left half of "p", one is right half of "p".
int[] left = Arrays.copyOfRange(p, 0, p.length/2);
int[] right = Arrays.copyOfRange(p, p.length/2, p.length);
// Find best values for buying and selling only in left array or only in right array
Trade best_left = BestTrade(left, 0, left.length-1);
Trade best_right = BestTrade(right, 0, right.length-1);
// Compute the best profit for buying in the left and selling in the right.
Trade best_both = new Trade(min(left), max(right), max(right) - min(left));
if (best_left.profit > best_right.profit && best_left.profit > best_both.profit)
return best_left;
else if (best_right.profit > best_left.profit && best_right.profit > best_both.profit)
return best_right;
else
return best_both;
}
public static int max(int[] A)
{
int max = 0;
for(int i=0; i < A.length; i++)
{
if(A[i] > max)
max = A[i];
}
return max;
}
public static int min(int[] A)
{
int min = 100000;
for(int i=0; i < A.length; i++)
{
if(A[i] < min)
min = A[i];
}
return min;
}
}
Once you have your array of numbers, you could simply run a for loop to detect the lowest value and the greatest value as well as the indices of each number.
int greatestDifference = 0;
int indexLowest = 0;
int indexHighest = 0;
for(int i = 0; i < values.length; i++)
for(int j = i + 1; j < values.length; j++)
if(values[i] - values[j] < greatestDifference){
greatestDifference = values[i] - values[j];
indexLowest = i;
indexHighest = j;
}
System.out.println("Buy value is " + values[indexLowest] + " on day " + (indexLowest + 1) + ".");
System.out.println("Sell value is " + values[indexHighest] + " on day " + (indexHighest + 1) + ".");
System.out.println("Net gain is " + Math.abs(greatestDifference));
Check it -
public class BuySellProfit {
public static void main(String[] args) {
int[] a = { 12, 45, 3, 15, 60, 23, 4 };
int min = a[0];
int max = a[0];
int minIndex=0;
int maxIndex=0;
for (int count = 0; count < a.length; count++) {
if (a[count] > max) {
max = a[count];
maxIndex=count;
}
}
System.out.println("Max = " + max);
for (int count = 0; count < a.length; count++) {
if (a[count] < min) {
min = a[count];
minIndex=count;
}
}
System.out.println("min=" + min);
profit(a, minIndex, maxIndex);
}
private static void profit(int a[], int i, int j) {
int profit = a[j] - a[i];
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(i);
list.add(j);
list.add(profit);
System.out.println(list);
}
}
Output :-
Max = 60
min=3
[2, 4, 57]
You just return the index number instead of Value,
It will work.. BTW your code is OK.
import java.util.Scanner;
public class Example4 {
public static void main(String[] args) {
//System.out.println("input the valuer:");
Scanner x =new Scanner(System.in);
for( int i=1;i<13;i++){
System.out.println("Profit for month" +i);
System.out.println("input the valuer :");
float valuer1 =x.nextFloat();
float result=0;
result+=valuer1;
System.out.println("Total profits for months:"+result);
}
}
}

Finding the second highest number in array

I'm having difficulty to understand the logic behind the method to find the second highest number in array. The method used is to find the highest in the array but less than the previous highest (which has already been found). The thing that I still can't figure it out is why || highest_score == second_highest is necessary. For example I input three numbers: 98, 56, 3. Without it, both highest and second highest would be 98. Please explain.
int second highest = score[0];
if (score[i] > second_highest && score[i] < highest_score || highest_score == second_highest)
second_highest = score[i];
I'm not convinced that doing what you did fixes the problem; I think it masks yet another problem in your logic. To find the second highest is actually quite simple:
static int secondHighest(int... nums) {
int high1 = Integer.MIN_VALUE;
int high2 = Integer.MIN_VALUE;
for (int num : nums) {
if (num > high1) {
high2 = high1;
high1 = num;
} else if (num > high2) {
high2 = num;
}
}
return high2;
}
This is O(N) in one pass. If you want to accept ties, then change to if (num >= high1), but as it is, it will return Integer.MIN_VALUE if there aren't at least 2 elements in the array. It will also return Integer.MIN_VALUE if the array contains only the same number.
// Initialize these to the smallest value possible
int highest = Integer.MIN_VALUE;
int secondHighest = Integer.MIN_VALUE;
// Loop over the array
for (int i = 0; i < array.Length; i++) {
// If we've found a new highest number...
if (array[i] > highest) {
// ...shift the current highest number to second highest
secondHighest = highest;
// ...and set the new highest.
highest = array[i];
} else if (array[i] > secondHighest)
// Just replace the second highest
secondHighest = array[i];
}
}
// After exiting the loop, secondHighest now represents the second
// largest value in the array
Edit: Whoops. Thanks for pointing out my mistake, guys. Fixed now.
If the first element which second_highest is set to initially is already the highest element, then it should be reassigned to a new element when the next element is found. That is, it's being initialized to 98, and should be set to 56. But, 56 isn't higher than 98, so it won't be set unless you do the check.
If the highest number appears twice, this will result in the second highest value as opposed to the second element that you would find if you sorted the array.
let array = [0,12,74,26,82,176,189,8,55,3,189];
let highest=0 ;
let secondHighest = 0;
for (let i = 0; i < array.length; i++) {
if (array[i] > highest) {
// ...shift the current highest number to second highest
secondHighest = highest;
// ...and set the new highest.
highest = array[i];
} else if (highest > array[i] > secondHighest) {
// Just replace the second highest
secondHighest = array[i];
}
}
console.log(secondHighest);
The answers I saw wont work if there are two same largest numbers like the below example.
int[] randomIntegers = { 1, 5, 4, 2, 8, 1, 8, 9,9 };
SortedSet<Integer> set = new TreeSet<Integer>();
for (int i: randomIntegers) {
set.add(i);
}
// Remove the maximum value; print the largest remaining item
set.remove(set.last());
System.out.println(set.last());
I have removed it from the Set not from the Array
My idea is that you assume that first and second members of the array are your first max and second max. Then you take each new member of an array and compare it with the 2nd max. Don't forget to compare 2nd max with the 1st one. If it's bigger, just swap them.
public static int getMax22(int[] arr){
int max1 = arr[0];
int max2 = arr[1];
for (int i = 2; i < arr.length; i++){
if (arr[i] > max2)
{
max2 = arr[i];
}
if (max2 > max1)
{
int temp = max1;
max1 = max2;
max2 = temp;
}
}
return max2;
}
public static int secondLargest(int[] input) {
int largest,secondLargest;
if(input[0] > input[1]) {
largest = input[0];
secondLargest = input[1];
}
else {
largest = input[1];
secondLargest = input[0];
}
for(int i = 2; i < input.length; i++) {
if((input[i] <= largest) && input[i] > secondLargest) {
secondLargest = input[i];
}
if(input[i] > largest) {
secondLargest = largest;
largest = input[i];
}
}
return secondLargest;
}
import java.util.Scanner;
public class SecondHighestFromArrayTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter size of Array");
int size = scan.nextInt();
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = scan.nextInt();
}
System.out.println("second highest element " + getSecondHighest(arr));
}
public static int getSecondHighest(int arr[]) {
int firstHighest = arr[0];
int secondHighest = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] > firstHighest) {
secondHighest = firstHighest;
firstHighest = arr[i];
} else if (arr[i] > secondHighest) {
secondHighest = arr[i];
}
}
return secondHighest;
}
}
If time complexity is not an issue, then You can run bubble sort and within two iterations, you will get your second highest number because in the first iteration of the loop, the largest number will be moved to the last. In the second iteration, the second largest number will be moved next to last.
If you want to 2nd highest and highest number index in array then....
public class Scoller_student {
public static void main(String[] args) {
System.out.println("\t\t\tEnter No. of Student\n");
Scanner scan = new Scanner(System.in);
int student_no = scan.nextInt();
// Marks Array.........
int[] marks;
marks = new int[student_no];
// Student name array.....
String[] names;
names = new String[student_no];
int max = 0;
int sec = max;
for (int i = 0; i < student_no; i++) {
System.out.println("\t\t\tEnter Student Name of id = " + i + ".");
names[i] = scan.next();
System.out.println("\t\t\tEnter Student Score of id = " + i + ".\n");
marks[i] = scan.nextInt();
if (marks[max] < marks[i]) {
sec = max;
max = i;
} else if (marks[sec] < marks[i] && marks[max] != marks[i]) {
sec = i;
}
}
if (max == sec) {
sec = 1;
for (int i = 1; i < student_no; i++) {
if (marks[sec] < marks[i]) {
sec = i;
}
}
}
System.out.println("\t\t\tHigherst score id = \"" + max + "\" Name : \""
+ names[max] + "\" Max mark : \"" + marks[max] + "\".\n");
System.out.println("\t\t\tSecond Higherst score id = \"" + sec + "\" Name : \""
+ names[sec] + "\" Max mark : \"" + marks[sec] + "\".\n");
}
}
public class secondLargestElement
{
public static void main(String[] args)
{
int []a1={1,0};
secondHigh(a1);
}
public static void secondHigh(int[] arr)
{
try
{
int highest,sec_high;
highest=arr[0];
sec_high=arr[1];
for(int i=1;i<arr.length;i++)
{
if(arr[i]>highest)
{
sec_high=highest;
highest=arr[i];
}
else
// The first condition before the || is to make sure that second highest is not actually same as the highest , think
// about {5,4,5}, you don't want the last 5 to be reported as the sec_high
// The other half after || says if the first two elements are same then also replace the sec_high with incoming integer
// Think about {5,5,4}
if(arr[i]>sec_high && arr[i]<highest || highest==sec_high)
sec_high=arr[i];
}
//System.out.println("high="+highest +"sec"+sec_high);
if(highest==sec_high)
System.out.println("All the elements in the input array are same");
else
System.out.println("The second highest element in the array is:"+ sec_high);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Not enough elements in the array");
//e.printStackTrace();
}
}
}
You can find Largest and Third largest number of unsorted array as well.
public class ThirdLargestNumber {
public static void main(String[] args) {
int arr[] = { 220, 200, 100, 100, 300, 600, 50, 5000, 125, 785 };
int first = 0, second = 0, third = 0, firstTemp = 0, secondTemp = 0;
for (int i = 0; i <= 9 /*
* Length of array-1. You can use here length
* property of java array instead of hard coded
* value
*/; i++) {
if (arr[i] == first) {
continue;
}
if (arr[i] > first) {
firstTemp = first;
secondTemp = second;
first = arr[i];
second = firstTemp;
if (secondTemp > third) {
third = secondTemp;
}
} else {
if ((arr[i] == second) || (arr[i]) == first) {
continue;
}
if ((arr[i] > second) && (arr[i]) < first) {
secondTemp = second;
second = arr[i];
if (secondTemp > third) {
third = secondTemp;
}
} else {
if (arr[i] > third) {
third = arr[i];
}
}
}
}
// System.out.println("Third largest number: " + third);
System.out.println("Second largest number: " + second);
// System.out.println("Largest number: " + first);
}
}
I think for finding the second Highest no we require these lines,if we can use inbuilt function
int[] randomIntegers = {1, 5, 4, 2, 8, 1, 1, 6, 7, 8, 9};
Arrays.sort(randomIntegers);
System.out.println(randomIntegers[randomIntegers.length-2]);
I am giving solution that's not in JAVA program (written in JavaScript), but it takes o(n/2) iteration to find the highest and second highest number.
Working fiddler link Fiddler link
var num=[1020215,2000,35,2,54546,456,2,2345,24,545,132,5469,25653,0,2315648978523];
var j=num.length-1;
var firstHighest=0,seoncdHighest=0;
num[0] >num[num.length-1]?(firstHighest=num[0],seoncdHighest=num[num.length-1]):(firstHighest=num[num.length-1], seoncdHighest=num[0]);
j--;
for(var i=1;i<=num.length/2;i++,j--)
{
if(num[i] < num[j] )
{
if(firstHighest < num[j]){
seoncdHighest=firstHighest;
firstHighest= num[j];
}
else if(seoncdHighest < num[j] ) {
seoncdHighest= num[j];
}
}
else {
if(firstHighest < num[i])
{
seoncdHighest=firstHighest;
firstHighest= num[i];
}
else if(seoncdHighest < num[i] ) {
seoncdHighest= num[i];
}
}
}
public class SecondandThirdHighestElement {
public static void main(String[] args) {
int[] arr = {1,1,2,3,8,1,2,3,3,3,2,3,101,6,6,7,8,8,1001,99,1,0};
// create three temp variable and store arr of first element in that temp variable so that it will compare with other element
int firsttemp = arr[0];
int secondtemp = arr[0];
int thirdtemp = arr[0];
//check and find first highest value from array by comparing with other elements if found than save in the first temp variable
for (int i = 0; i < arr.length; i++) {
if(firsttemp <arr[i]){
firsttemp = arr[i];
}//if
}//for
//check and find the second highest variable by comparing with other elements in an array and find the element and that element should be smaller than first element array
for (int i = 0; i < arr.length; i++) {
if(secondtemp < arr[i] && firsttemp>arr[i]){
secondtemp = arr[i];
}//if
}//for
//check and find the third highest variable by comparing with other elements in an array and find the element and that element should be smaller than second element array
for (int i = 0; i < arr.length; i++) {
if(thirdtemp < arr[i] && secondtemp>arr[i]){
thirdtemp = arr[i];
}//if
}//for
System.out.println("First Highest Value:"+firsttemp);
System.out.println("Second Highest Value:"+secondtemp);
System.out.println("Third Highest Value:"+thirdtemp);
}//main
}//class
If this question is from the interviewer then please DONT USE SORTING Technique or Don't use any built in methods like Arrays.sort or Collection.sort. The purpose of this questions is how optimal your solution is in terms of performance so the best option would be just implement with your own logic with O(n-1) implementation. The below code is strictly for beginners and not for experienced guys.
public void printLargest(){
int num[] ={ 900,90,6,7,5000,4,60000,20,3};
int largest = num[0];
int secondLargest = num[1];
for (int i=1; i<num.length; i++)
{
if(largest < num[i])
{
secondLargest = largest;
largest = num[i];
}
else if(secondLargest < num[i]){
secondLargest = num[i];
}
}
System.out.println("Largest : " +largest);
System.out.println("Second Largest : "+secondLargest);
}
Problem:
The problem is to get the second largest array element.
Observation:
Second largest number is defined as the number that has the minimum difference when subtracted from the maximum element in the array.
Solution:
This is a two pass solution. First pass is to find the maximum number. Second pass is to find the element that has minimum difference with the maximum element as compared to other array elements. Example: In the array [2, 3, 6, 6, 5] maximum = 6 and second maximum = 5 , since it has the minimum difference to the maximum element 6 - 5 = 1 the solution for second largest = 5
function printSecondMax(myArray) {
var x, max = myArray[0];
// Find maximum element
for(x in myArray){
if(max < myArray[x]){
max = myArray[x];
}
}
var secondMax = myArray[0], diff = max - secondMax;
// Find second max, an element that has min diff with the max
for(x in myArray){
if(diff != 0 && (max - myArray[x]) != 0 && diff > (max - myArray[x])){
secondMax = myArray[x];
diff = max - secondMax;
}
}
console.log(secondMax);
}
Complexity : O(n), This is the simplest way to do this.
For finding maximum element even more efficiently one can look into max heap, a call to max-heapify will take O(log n) time to find the max and then pop-ing the top element gives maximum. To get the second maximum, max-heapify after pop-ing the top and keep pop-ing till you get a number that is less than maximum. That will be the second maximum. This solution has O(n log n) complexity.
private static int SecondBiggest(int[] vector)
{
if (vector == null)
{
throw new ArgumentNullException("vector");
}
if (vector.Length < 2)
{
return int.MinValue;
}
int max1 = vector[0];
int max2 = vector[1];
for (int i = 2; i < vector.Length; ++i)
{
if (max1 > max2 && max1 != vector[i])
{
max2 = Math.Max(max2, vector[i]);
}
else if (max2 != vector[i])
{
max1 = Math.Max(max1, vector[i]);
}
}
return Math.Min(max1, max2);
}
This treats duplicates as the same number. You can change the condition checks if you want to all the biggest and the second biggest to be duplicates.
Please try this one: Using this method, You can fined second largest number in array even array contain random number. The first loop is used to solve the problem if largest number come first index of array.
public class secondLargestnum {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] array = new int[6];
array[0] = 10;
array[1] = 80;
array[2] = 5;
array[3] = 6;
array[4] = 50;
array[5] = 60;
int tem = 0;
for (int i = 0; i < array.length; i++) {
if (array[0]>array[i]) {
tem = array[0];
array[0] = array[array.length-1];
array[array.length-1] = tem;
}
}
Integer largest = array[0];
Integer second_largest = array[0];
for (int i = 0; i < array.length; i++) {
if (largest<array[i]) {
second_large = largest;
largest = array[i];
}
else if (second_large<array[i]) {
second_large = array[i];
}
}
System.out.println("largest number "+largest+" and second largest number "+second_largest);
}
}
public class SecondHighInIntArray {
public static void main(String[] args) {
int[] intArray=new int[]{2,2,1};
//{2,2,1,12,3,7,9,-1,-5,7};
int secHigh=findSecHigh(intArray);
System.out.println(secHigh);
}
private static int findSecHigh(int[] intArray) {
int highest=Integer.MIN_VALUE;
int sechighest=Integer.MIN_VALUE;
int len=intArray.length;
for(int i=0;i<len;i++)
{
if(intArray[i]>highest)
{
sechighest=highest;
highest=intArray[i];
continue;
}
if(intArray[i]<highest && intArray[i]>sechighest)
{
sechighest=intArray[i];
continue;
}
}
return sechighest;
}
}
Second Largest in O(n/2)
public class SecMaxNum {
// second Largest number with O(n/2)
/**
* #author Rohan Kamat
* #Date Feb 04, 2016
*/
public static void main(String[] args) {
int[] input = { 1, 5, 10, 11, 11, 4, 2, 8, 1, 8, 9, 8 };
int large = 0, second = 0;
for (int i = 0; i < input.length - 1; i = i + 2) {
// System.out.println(i);
int fist = input[i];
int sec = input[i + 1];
if (sec >= fist) {
int temp = fist;
fist = sec;
sec = temp;
}
if (fist >= second) {
if (fist >= large) {
large = fist;
} else {
second = fist;
}
}
if (sec >= second) {
if (sec >= large) {
large = sec;
} else {
second = sec;
}
}
}
}
}
public class SecondHighest {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* Find the second largest int item in an unsorted array.
* This solution assumes we have atleast two elements in the array
* SOLVED! - Order N.
* Other possible solution is to solve with Array.sort and get n-2 element.
* However, Big(O) time NlgN
*/
int[] nums = new int[]{1,2,4,3,5,8,55,76,90,34,91};
int highest,cur, secondHighest = -1;
int arrayLength = nums.length;
highest = nums[1] > nums[0] ? nums[1] : nums[0];
secondHighest = nums[1] < nums[0] ? nums[1] : nums[0];
if (arrayLength == 2) {
System.out.println(secondHighest);
} else {
for (int x = 0; x < nums.length; x++) {
cur = nums[x];
int tmp;
if (cur < highest && cur > secondHighest)
secondHighest = cur;
else if (cur > secondHighest && cur > highest) {
tmp = highest;
highest = cur;
secondHighest = tmp;
}
}
System.out.println(secondHighest);
}
}
}
Use following function
`
public static int secHigh(int arr[]){
int firstHigh = 0,secHigh = 0;
for(int x: arr){
if(x > firstHigh){
secHigh = firstHigh;
firstHigh = x;
}else if(x > secHigh){
secHigh = x;
}
}
return secHigh;
}
Function Call
int secondHigh = secHigh(arr);
import java.util.Scanner;
public class SecondLargest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter size of array : ");
int n = sc.nextInt();
int ar[] = new int[n];
for(int i=0;i<n;i++)
{
System.out.print("Enter value for array : ");
ar[i] = sc.nextInt();
}
int m=ar[0],m2=ar[0];
for(int i=0;i<n;i++)
{
if(ar[i]>m)
m=ar[i];
}
for(int i=0;i<n;i++)
{
if(ar[i]>m2 && ar[i]<m)
m2=ar[i];
}
System.out.println("Second largest : "+m2);
sc.close();
}
}
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 retrived 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.
public class SecondLargestNumber
{
public static void main(String[] args)
{
int[] var={-11,-11,-11,-11,115,-11,-9};
int largest = 0;
int secLargest = 0;
if(var.length == 1)
{
largest = var[0];
secLargest = var[0];
}
else if(var.length > 1)
{
largest= var[0];
secLargest = var[1];
for(int i=1;i<var.length;i++)
{
if(secLargest!=largest)
{
if(var[i]>largest)
{
secLargest = largest;
largest = var[i];
}
else if(var[i]>secLargest && var[i] != largest)
{
secLargest= var[i];
}
}
else
{
if(var[i]>largest)
{
secLargest = largest;
largest = var[i];
}
else
{
secLargest = var[i];
}
}
}
}
System.out.println("Largest: "+largest+" Second Largest: "+secLargest);
}
}
/* Function to print the second largest elements */
void print2largest(int arr[], int arr_size)
{
int i, first, second;
/* There should be atleast two elements */
if (arr_size < 2)
{
printf(" Invalid Input ");
return;
}
first = second = INT_MIN;
for (i = 0; i < arr_size ; i ++)
{
/* If current element is smaller than first
then update both first and second */
if (arr[i] > first)
{
second = first;
first = arr[i];
}
/* If arr[i] is in between first and
second then update second */
else if (arr[i] > second && arr[i] != first)
second = arr[i];
}
if (second == INT_MIN)
printf("There is no second largest elementn");
else
printf("The second largest element is %dn", second);
}
I have got the simplest logic to find the second largest number may be, it's not.
The logic find sum of two number in the array which has the highest value and then check which is greater among two simple............
int ar[]={611,4,556,107,5,55,811};
int sum=ar[0]+ar[1];
int temp=0;
int m=ar[0];
int n=ar[1];
for(int i=0;i<ar.length;i++){
for(int j=i;j<ar.length;j++){
if(i!=j){
temp=ar[i]+ar[j];
if(temp>sum){
sum=temp;
m=ar[i];
n=ar[j];
}
temp=0;
}
}
}
if(m>n){
System.out.println(n);
}
else{
System.out.println(m);
}
The simplest way is -
public class SecondLargest {
public static void main(String[] args) {
int[] arr = { 1, 2, 5, 6, 3 };
int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
// If current element is smaller than first then update both first
// and second
if (arr[i] > first) {
second = first;
first = arr[i];
}
// If arr[i] is in between first and second then update second
else if (arr[i] > second && arr[i] != first) {
second = arr[i];
}
}
}
}
The second largest element in the array :
IN Java:
class test2{
public static void main(String[] args) {
int a[] = {1,2,3,9,5,7,6,4,8};
Arrays.sort(a);
int aa = a[a.length -2 ];
System.out.println(aa);
}//main
}//end
In Python :
a = [1, 2, 3, 9, 5, 7, 6, 4, 8]
aa = sorted(list(a))
print(aa)
aaa = aa[-2]
print(aaa)

Categories

Resources