How to swap the position of the numbers - java

I'm new to Java programming and I want to know how to swap the position of the highest number and the lowest number.
import java.util.*;
public class HighestandLowestNum
{
static Scanner data = new Scanner (System.in);
public static void main(String[]args)
{
int num [] = new int [10];
int i;
System.out.println("Enter 10 numbers: ");
for (i = 0; i < num.length; i++)
{
num [i] = data.nextInt();
Highest(num);
Lowest(num);
}
System.out.println("The highest number is: " + Highest(num));
System.out.println("The lowest number is: " + Lowest(num));
}
public static int Highest(int[] num)
{
int highest = num[0];
int i;
for (i = 1; i < num.length; i++)
{
if (num[i] > highest)
{
highest = num[i];
}
}
return highest;
}
public static int Lowest(int[] num)
{
int lowest = num[0];
int i;
for (i = 1; i < num.length; i++)
{
if (num[i] < lowest)
{
lowest = num[i];
}
}
return lowest;
}
}
This is my program. Please help me to fix my problem.

Your two functions Highest and Lowest return the value of the highest and lowest numbers. In order to swap them, you need to know the positions those values have within the array.
If you alter those functions or create new ones to return the index of the highest and lowest values, then you can swap them with what you've probably already seen before:
pseudocode:
temp = first
first = last
last = temp

To Swap the two numbers in the array, you need to know the numbers and their position as mentioned in the earlier answers. You can modify the two functions in such a way that they provide Numbers as well as their Position. One way to do this is to return an array instead of integer from the function. And in that array, information about the number and its position can be encapsulated. Ill show you what I mean in the code I am providing:
static Scanner data = new Scanner (System.in);
public static void main(String[]args)
{
int num []= new int [10];
int i;
System.out.println("Enter 10 numbers: ");
for (i = 0; i <num.length; i++)
{
num [i] = data.nextInt();
Highest(num);
Lowest(num);
}
System.out.print("The original array is");
for (i = 0; i <num.length; i++)
{
System.out.print(" "+num[i]);
}
System.out.println("");
int highest = Highest(num)[0];
int lowest = Lowest(num)[0];
int highestPosition = Highest(num)[1];
int lowestPosition = Lowest(num)[1];
System.out.println("The highest number is: " +highest+" at position "+highestPosition);
System.out.println("The lowest number is: " +lowest+" at position "+lowestPosition);
//Swap//
num[highestPosition] = lowest;
num[lowestPosition] = highest;
System.out.print("The new array is");
for (i = 0; i <num.length; i++)
{
System.out.print(" "+num[i]);
}
}
public static int[] Highest(int[] num)
{
int highest = num[0];
int i;
int index = 0;
int[] result = {highest,index};
for (i = 1; i <num.length;i++)
{
if (num[i] > highest)
{
highest = num[i];
index = i;
result[0] = highest;
result[1] = index;
}
}
return result;
}
public static int[] Lowest(int[] num)
{
int lowest = num[0];
int i;
int index = 0;
int[] result = {lowest,index};
for (i = 1; i <num.length;i++)
{
if (num[i] < lowest)
{
lowest = num[i];
index = i;
result[0] = lowest;
result[1] = index;
}
}
return result;
}
Try reading the modification in the Highest and Lowest functions and than go through the main code. Hope this helps.

Related

Finding largest gap between consecutive numbers in array Java

I'm currently working on a homework assignment and the final task of the assignment is to write a method to find the largest gap between consecutive numbers in an unsorted array. Example: if the array had the values {1,2,3,4,5,20} the gap would be 15. Currently the array is holding 20 values generated at random.
I'm totally lost for how I would make this happen. Initially my idea for how to solve this would be using a for loop which runs through each value of the array with another loop inside to check if the current value is equal to the previous value plus 1. If it is then store that number as the minimum in the range. Another problem I ran into was that I have no idea how to store a second number without overwriting both numbers in the range. Basically nothing i've tried is working and could really use some help or at least a nudge in the right direction.
What the method does right now is only store the value for "a" after it finds a number that isn't consecutive in the array.
Here's the code I have so far
import java.util.Arrays;
class Main {
public static void main(String[] args) {
Main m = new Main();
m.runCode();
}
public void runCode()
{
Calculator calc = new Calculator();
calc.makeList(20);
System.out.println("List:");
calc.showList();
System.out.println("Max is: " + calc.max());
System.out.println("Min is: " + calc.min());
System.out.println("Sum is: " + calc.sum());
System.out.println("Ave is: " + calc.average());
System.out.println("There are " + calc.fiftyLess() + " values in the list that are less than 50");
System.out.println("Even numbers: " + calc.Even());
}
}
class Calculator {
int list[] = new int[20];
public void makeList(int listSize)
{
for (int count = 0; count < list.length; count++) {
list[count] = (int) (Math.random() * 100);
}
}
public void showList()
{
for (int count = 0; count < list.length; count++)
{
System.out.print(list[count] + " ");
}
}
public int max()
{
int max = list[0];
for (int count=0; count<list.length; count++){
if (list[count] > max) {
max = list[count];
}
}
return max;
}
public int min()
{
int min = list[0];
for (int count=0; count<list.length; count++){
if (list[count] < min) {
min = list[count];
}
}
return min;
}
public int sum()
{
int sum = 0;
for (int count=0; count<list.length; count++){
sum = sum + list[count];
}
return sum;
}
public double average()
{
int sum = sum();
double average = sum / list.length;
return average;
}
public int fiftyLess()
{
int lessThan = 0;
for (int count =0; count<list.length;count++)
{
if (list[count] < 50)
{
lessThan++;
}
}
return lessThan;
}
public int Even()
{
int isEven = 0;
for (int count = 0; count<list.length;count++)
{
if (list[count] % 2 == 0)
{
isEven++;
}
}
return isEven;
}
public int Gap()
{
int a = 0;
int b = 0;
int gap = math.abs(a - b);
for (int count = 1; count<list.length;count++)
{
if (list[count] != list[count] + 1)
{
a =list[count];
}
}
}
}
By using the java8 stream library you could achieve this in fewer lines of code.
This code segment iterates the range of the array, and subtracts all consecutive numbers, and returns the max difference between them or -1, in case the array is empty.
import java.util.stream.IntStream;
class Main {
public static void main(String[] args) {
int[] list = {1, 2, 3, 4, 5, 20};
int max_difference =
IntStream.range(0, list.length - 1)
.map(i -> Math.abs(list[i + 1] - list[i]))
.max().orElse(-1);
System.out.println(max_difference);
}
}
Alternatively you could do this with a traditional for loop.
class Main {
public static void main(String[] args) {
int[] list = {1, 2, 3, 4, 5, 20};
int max_difference = -1;
int difference;
for (int i = 0; i < list.length - 1; i++) {
difference = Math.abs(list[i + 1] - list[i]);
if(difference > max_difference)
max_difference = difference;
}
System.out.println(max_difference);
}
}
Output for both code segments:
15

how swap between two array values?

When user enter number 1 smaller than number 2 swap does not work,
but when number 1 is larger than number 2 it works. I don't understand why this is occurring. I would appreciate some suggestions or help.
package javaapplication36;
public class JavaApplication36 {
static Scanner s = new Scanner(System.in);
// main method
public static void main(String[] args) {
int[] arr = new int[10];
input(arr);
System.out.println("Enter n1 :");
int n1 = s.nextInt();
System.out.println("Enter n2 : ");
int n2 = s.nextInt();
display(arr);
int temp = 0;
int index_a = index(arr, n1);
int index_b = index(arr, n2);
if (index(arr, n1) != -1 && index(arr, n2) != -1) {
temp = arr[index_a];
arr[index_a] = arr[index_b];
arr[index_b] = temp;
}
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
public static void display(int[] arr) {
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
public static void input(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.println("Enter number : " + (i + 1));
arr[i] = s.nextInt();
}
}
public static int index(int[] arr, int n) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == n)
return i;
}
return -1;
}
}
I tried this and could not find anything wrong. To make debugging this easier I recommend you populate your array using random numbers.
Create an instance of Random
Random rand = new Random();
And assign the output to your array variable.
arr = rand.ints(10,1,15).toArray();
The arguments to rand.ints are.
10 - the number of elements
1 - the start of the range of numbers
15 - the end of the range (not including that number)
So that call would generate 10 numbers from 1 to 14 inclusive.
One possibility for any problems could be duplicate numbers in your array and finding the correct one to swap. But I was unable to reproduce the error.

Loading space-separated user input to array

I'm new to Java. I've spent hours trying to figure out why this code doesn't work. It's supposed to take user input integers separated by whitespace, and load them into an int array. Then, the numbers are supposed to be sorted in descending order, and the frequency of repeated inputs has to be displayed in a separate int array.
I'm getting zeroes in the output though. Can anyone help me fix this program?
This is what I have:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] inputNumbers = new int[50];
int[] ocurrences = new int[50];
int size = 0;
System.out.println("How many numbers to enter? (At most 50)");
size = input.nextInt();
System.out.println("Enter eaach of the numbers. Please put a space between each number.");
String arrayString = input.next();
input = new Scanner(arrayString);
while(input.hasNextInt())
{
int nextNumber = input.nextInt();
if(!isInArray(inputNumbers, size, nextNumber))
{
inputNumbers[size] = nextNumber;
ocurrences[size] = 1;
size++;
}
else
{
int index = search(inputNumbers, size, nextNumber);
ocurrences[index]++;
}
}
sort(inputNumbers, ocurrences, size);
System.out.println("N\t\tCount");
for(int i = 0; i < size; i++)
{
System.out.println(inputNumbers[i] + "\t\t" + ocurrences[i]);
}
}
public static void sort(int[] inputNumbers, int[] ocurrences, int size)
{
for(int current = 0; current < size; current++)
{
int max = current;
for(int i = current; i < size; i++)
{
if(inputNumbers[i] > inputNumbers[max])
max = i;
}
int temp = inputNumbers[max];
inputNumbers[max] = inputNumbers[current];
inputNumbers[current] = temp;
temp = ocurrences[max];
ocurrences[max] = ocurrences[current];
ocurrences[current] = temp;
}
}
public static int search(int[] array, int size, int number)
{
for(int i = 0; i < size; i++)
{
if(array[i] == number)
return i;
}
return -1;
}
public static boolean isInArray(int[] array, int size, int number)
{
for(int i = 0; i < size; i++)
{
if(array[i] == number)
return true;
}
return false;
}
}
The current output is:
How many numbers to enter? (At most 50)
4
Enter eaach of the numbers. Please put a space between each number.
5 5 4 7 8
N Count
5 1
0 0
0 0
0 0
0 0
BUILD SUCCESSFUL (total time: 11 seconds)
It should have been something like
N Count
8 1
7 1
5 2
4 1
Initialize the array where we know the exact size, so it avoid unnecessary memory utilization.
Also input.next() will read only the next complete token not the entire line. That was the mistake in the code.
Finally the scanner resource was not closed.
I have refactored your code, please check it.
public static void main(String[] args) {
Scanner input = null;
try {
input = new Scanner(System.in);
int[] inputNumbers, ocurrences;
int index = 0, size;
System.out.println("How many numbers to enter? (At most 50)");
size = input.nextInt();
inputNumbers = new int[size];
ocurrences = new int[size];
System.out.println("Enter each of the numbers. Please put a space between each number.");
for (int i = 0; i < size; i++) {
int nextNumber = input.nextInt();
if (!isInArray(inputNumbers, nextNumber)) {
inputNumbers[index] = nextNumber;
ocurrences[index] = 1;
index++;
} else {
int oIndex = search(inputNumbers, nextNumber);
ocurrences[oIndex] ++;
}
}
sort(inputNumbers, ocurrences);
System.out.println("N\t\tCount");
for (int i = 0; i < index; i++) {
System.out.println(inputNumbers[i] + "\t\t" + ocurrences[i]);
}
} finally {
input.close();
}
}
public static void sort(int[] inputNumbers, int[] ocurrences) {
int size = inputNumbers.length;
for (int current = 0; current < size; current++) {
int max = current;
for (int i = current; i < size; i++) {
if (inputNumbers[i] > inputNumbers[max])
max = i;
}
int temp = inputNumbers[max];
inputNumbers[max] = inputNumbers[current];
inputNumbers[current] = temp;
temp = ocurrences[max];
ocurrences[max] = ocurrences[current];
ocurrences[current] = temp;
}
}
public static int search(int[] array, int number) {
int size = array.length;
for (int i = 0; i < size; i++) {
if (array[i] == number)
return i;
}
return -1;
}
public static boolean isInArray(int[] array, int number) {
int size = array.length;
for (int i = 0; i < size; i++) {
if (array[i] == number)
return true;
}
return false;
}

Getting the largest element in an array using recursion

I have an assignment to use recursion to obtain the largest element in any given array. I have the following code which will work unless the largest element is the last in the array.
Not sure how to correct this?
import java.util.Scanner;
public class RecursionLargestInArray
{
public static void main (String[] args)
{
int max = -999;
Scanner scan = new Scanner (System.in);
System.out.print("Enter the size of the array: ");
int arraySize = scan.nextInt();
int[] myArray = new int[arraySize];
System.out.print("Enter the " + arraySize + " values of the array: ");
for (int i = 0; i < myArray.length; i++)
myArray[i] = scan.nextInt();
for (int i = 0; i < myArray.length; i++)
System.out.println(myArray[i]);
System.out.println("In the array entered, the larget value is "
+ getLargest(myArray, max) + ".");
}
public static int getLargest(int[] myArray, int max)
{
int i = 0, j = 0, tempmax = 0;
if (myArray.length == 1)
{
return max;
}
else if (max < myArray[i])
{
max = myArray[i];
int[] tempArray = new int[myArray.length-1];
for (i = 1; i < myArray.length; i++)
{
tempArray[j] = myArray[i];
j++;
}
tempmax = getLargest(tempArray, max);
return tempmax;
}
else if
{
int[] tempArray = new int[myArray.length-1];
for (i = 1; i < myArray.length; i++)
{
tempArray[j] = myArray[i];
j++;
}
tempmax = getLargest(tempArray, max);
return tempmax;
}
}
}
Your first condition is the problem:
if (myArray.length == 1)
{
return max;
}
replace it with:
if (myArray.length == 1)
{
return myArray[0] > max ? myArray[0] : max;
}
In case of an array with only one element, you return the previous maximum. If the max is that last element, it will be skipped.
you never evaluate the final element - you simply return max when the size of the array is 1, so you never actually check the final element in the array.
also, a comment - rather than creating copies of the array each time, why don't you simply pass the current index into your function every time you recurse?
When the array length is 1, getLargest isn't testing the (single) array element against max; it's just returning max. That's why it's always skipping the last element.
As an aside, it would be better to initialize max to Integer.MIN_VALUE instead of to an arbitrary value of -999.
As a further aside, once you get your code working, it will still be terribly inefficient. You might consider posting it to codereview.stackexchange.com to get feedback.
how about divide and conquer?
private static int findLargest(int lowerLimit, int upperLimit) {
if (lowerLimit == upperLimit) {
return temp[lowerLimit];
} else if (upperLimit - lowerLimit == 1){
return Math.max(temp[upperLimit], temp[lowerLimit]);
} else {
int pivot = (upperLimit - lowerLimit + 1)/2;
int firstHalf = findLargest(lowerLimit, lowerLimit + pivot);
int secondHalf = findLargest(upperLimit - pivot , upperLimit);
return Math.max(firstHalf, secondHalf);
}
}
of course temp is the global array.. and to start the recursion you call it with findLargest(0,temp.length)

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