Getting the most "popular" number from array - java

I need for homework to get the most "popular" number in an array (the number in the highest frequency), and if there are several numbers with the same number of shows, get some number randomly.
After more then three hours of trying, and either searching the web, this is what I got:
public int getPopularNumber(){
int count = 1, tempCount;
int popular = array[0];
int temp = 0;
for ( int i = 0; i < (array.length - 1); i++ ){
if ( _buses[i] != null )
temp = array[i];
tempCount = 0;
for ( int j = 1; j < _buses.length; j++ ){
if ( array[j] != null && temp == array[j] )
tempCount++;
}
if ( tempCount > count ){
popular = temp;
count = tempCount;
}
}
return popular;
}
This code work, but don't take into account an important case- if there is more than one number with the same count of shows. Then it just get the first one.
for example: int[]a = {1, 2, 3, 4, 4, ,5 ,4 ,5 ,5}; The code will grab 4 since it shown first, and it's not random as it should be.
Another thing- since it's homework I can't use ArrayList/maps and stuff that we still didn't learn.
Any help would be appreciated.

Since they didn't give you any time complexity boundary, you can "brute force" the problem by scanning the the array N^2 times. (disclaimer, this is the most intuitive way of doing it, not the fastest or the most efficient in terms of memory and cpu).
Here is some psuedo-code:
Create another array with the same size as the original array, this will be the "occurrence array"
Zero its elements
For each index i in the original array, iterate the original array, and increment the element in the occurrence array at i each time the scan finds duplicates of the value stored in i in the original array.
Find the maximum in the occurrence array
Return the value stored in that index in the original array
This way you mimic the use of maps with just another array.

If you are not allowed to use collection then you can try below code :
public int getPopularNumber(){
int inputArr[] = {1, 2, 3, 4, 4, 5 ,4 ,5 ,5}; // given input array
int[] tempArr = new int[inputArr.length];
int[] maxValArr = new int[inputArr.length];
// tempArr will have number as index and count as no of occurrence
for( int i = 0 ; i < inputArr.length ; i++){
tempArr[inputArr[i]]++;
}
int maValue = 0;
// find out max count of occurrence (in this case 3 for value 4 and 5)
for( int j = 0 ; j < tempArr.length ; j++){
maValue = Math.max(maValue, tempArr[j]);
}
int l =0;
// maxValArr contains all value having maximum occurrence (in this case 4 and 5)
for( int k = 0 ; k < tempArr.length ; k++){
if(tempArr[k] == maValue){
maxValArr[l] = k;
l++;
}
}
return maxValArr[(int)(Math.random() * getArraySize(maxValArr))];
}
private int getArraySize(int[] arr) {
int size = 0;
for( int i =0; i < arr.length ; i++){
if(arr[i] == 0){
break;
}
size++;
}
return size;
}

that's hard as hell :D
After some trying, I guess I have it (If there will be 2 numbers with same frequency, it will return first found):
int mostPopNumber =0;
int tmpLastCount =0;
for (int i = 0; i < array.length-1; i++) {
int tmpActual = array[i];
int tmpCount=0;
for (int j = 0; j < array.length; j++) {
if(tmpActual == array[j]){
tmpCount++;
}
}
// >= for the last one
if(tmpCount > tmpLastCount){
tmpLastCount = tmpCount;
mostPopNumber = tmpActual;
}
}
return mostPopNumber;
--
Hah your code give me idea- you cant just remember last most popular number, btw I've found it solved there Find the most popular element in int[] array
:)
EDIT- after many, and many years :D, that works well :)
I've used 2D int and Integer array - you can also use just int array, but you will have to make more length array and copy actual values, Integer has default value null, so that's faster
Enjoy
public static void main(String[] args) {
//income array
int[] array= {1,1,1,1,50,10,20,20,2,2,2,2,20,20};
//associated unique numbers with frequency
int[][] uniQFreqArr = getUniqValues(array);
//print uniq numbers with it's frequency
for (int i = 0; i < uniQFreqArr.length; i++) {
System.out.println("Number: " + uniQFreqArr[i][0] + " found : " + uniQFreqArr[i][1]);
}
//get just most frequency founded numbers
int[][] maxFreqArray = getMaxFreqArray(uniQFreqArr);
//print just most frequency founded numbers
System.out.println("Most freq. values");
for (int i = 0; i < maxFreqArray.length; i++) {
System.out.println("Number: " + maxFreqArray[i][0] + " found : " + maxFreqArray[i][1]);
}
//get some of found values and print
int[] result = getRandomResult(maxFreqArray);
System.out.println("Found most frequency number: " + result[0] + " with count: " + result[1]);
}
//get associated array with unique numbers and it's frequency
static int[][] getUniqValues(int[] inArray){
//first time sort array
Arrays.sort(inArray);
//default value is null, not zero as in int (used bellow)
Integer[][] uniqArr = new Integer[inArray.length][2];
//counter and temp variable
int currUniqNumbers=1;
int actualNum = inArray[currUniqNumbers-1];
uniqArr[currUniqNumbers-1][0]=currUniqNumbers;
uniqArr[currUniqNumbers-1][1]=1;
for (int i = 1; i < inArray.length; i++) {
if(actualNum != inArray[i]){
uniqArr[currUniqNumbers][0]=inArray[i];
uniqArr[currUniqNumbers][1]=1;
actualNum = inArray[i];
currUniqNumbers++;
}else{
uniqArr[currUniqNumbers-1][1]++;
}
}
//get correctly lengthed array
int[][] ret = new int[currUniqNumbers][2];
for (int i = 0; i < uniqArr.length; i++) {
if(uniqArr[i][0] != null){
ret[i][0] = uniqArr[i][0];
ret[i][1] = uniqArr[i][1];
}else{
break;
}
}
return ret;
}
//found and return most frequency numbers
static int[][] getMaxFreqArray(int[][] inArray){
int maxFreq =0;
int foundedMaxValues = 0;
//filter- used sorted array, so you can decision about actual and next value from array
for (int i = 0; i < inArray.length; i++) {
if(inArray[i][1] > maxFreq){
maxFreq = inArray[i][1];
foundedMaxValues=1;
}else if(inArray[i][1] == maxFreq){
foundedMaxValues++;
}
}
//and again copy to correctly lengthed array
int[][] mostFreqArr = new int[foundedMaxValues][2];
int inArr= 0;
for (int i = 0; i < inArray.length; i++) {
if(inArray[i][1] == maxFreq){
mostFreqArr[inArr][0] = inArray[i][0];
mostFreqArr[inArr][1] = inArray[i][1];
inArr++;
}
}
return mostFreqArr;
}
//generate number from interval and get result value and it's frequency
static int[] getRandomResult(int[][] inArray){
int[]ret=new int[2];
int random = new Random().nextInt(inArray.length);
ret[0] = inArray[random][0];
ret[1] = inArray[random][1];
return ret;
}

Related

Count the Number of Swaps in Selection Sort

I've read through all the discussions trying to find an answer but none of the answers have worked for me so I'm trying it this way.
public static int SelectionSort(long[] num)
{
int i, j, first;
long temp;
int swap = 0;
int pass = 0;
int count = 0;
boolean Mini = false;
for (i = num.length - 1; i > 0; i--)
{
for(int k = 0; k < num.length; k++)
{
System.out.println(" k = " + k
+ " \t X[i] = " + num[k] + " swap count: " + swap);
}
System.out.println("");
first = 0; //initialize to subscript of first element
for(j = 1; j <= i; j ++) //locate smallest element between positions 1 and i.
{
if(num[j] < num[first])
{
first = j;
//Mini = true;
}
}
//if(Mini){
// swap++;
//}
temp = num[first]; //swap smallest found with element in position i.
num[first] = num[i];
num[i] = temp;
}
return swap;
}
Using a simple array as my test case:
long[] X = {1, 4, 3, 2, 5};
The number of swaps should only equate to 1 because it's swapping the first and last elements only. However, it isn't working. While I know my if condition doesn't work, I can't think of what would. I can't seem to work the logic that it increments a swap when items are actually swapped.
Why not increment the counter when you actually perform a swap?
//swap smallest found with element in position i.
swap++
temp = num[first];
num[first] = num[i];
num[i] = temp;
EDIT:
Good point in the comment. The current code still performs a superfluous swap if the array is sorted (i.e., first and i are the same):
if (first != i) {
swap++
temp = num[first];
num[first] = num[i];
num[i] = temp;
}
With your implementation you will always have n swaps (where n is the number of elements in your array).
What I think you want is to only perform a swap when it actually makes a difference ... so when "first" and "i" have different values. Otherwise you switch the element with itself.
if (first != i) {
temp = num[first];
num[first] = num[i];
num[i] = temp;
swapp++;
}

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");

Given an array with 2 integers that repeat themselves the same no. of times, how do i print the two integers

i'm new to this, Say if you typed 6 6 6 1 4 4 4 in the command line, my code gives the most frequent as only 6 and i need it to print out 6 and 4 and i feel that there should be another loop in my code
public class MostFrequent {
//this method creates an array that calculates the length of an integer typed and returns
//the maximum integer...
public static int freq(final int[] n) {
int maxKey = 0;
//initiates the count to zero
int maxCounts = 0;
//creates the array...
int[] counts = new int[n.length];
for (int i=0; i < n.length; i++) {
for (int j=0; j < n[i].length; j++)
counts[n[i][j]]++;
if (maxCounts < counts[n[i]]) {
maxCounts = counts[n[i]];
maxKey = n[i];
}
}
return maxKey;
}
//method mainly get the argument from the user
public static void main(String[] args) {
int len = args.length;
if (len == 0) {
//System.out.println("Usage: java MostFrequent n1 n2 n3 ...");
return;
}
int[] n = new int[len + 1];
for (int i=0; i<len; i++) {
n[i] = Integer.parseInt(args[i]);
}
System.out.println("Most frequent is "+freq(n));
}
}
Thanks...enter code here
Though this may not be a complete solution, it's a suggestion. If you want to return more than one value, your method should return an array, or better yet, an ArrayList (because you don't know how many frequent numbers there will be). In the method, you can add to the list every number that is the most frequest.
public static ArrayList<Integer> freq(final int[] n) {
ArrayList<Integer> list = new ArrayList<>();
...
if (something)
list.add(thatMostFrequentNumber)
return list;
}
The solutions looks like this:
// To use count sort the length of the array need to be at least as
// large as the maximum number in the list.
int[] counts = new int[MAX_NUM];
for (int i=0; i < n.length; i++)
counts[n[i]]++;
// If your need more than one value return a collection
ArrayList<Integer> mf = new ArrayList<Integer>();
int max = 0;
for (int i = 0; i < MAX_NUM; i++)
if (counts[i] > max)
max = counts[i];
for (int i = 0; i < MAX_NUM; i++)
if (counts[i] == max)
mf.add(i);
return mf;
Well you can just do this easily by using the HashTable class.
Part 1. Figure out the frequency of each number.
You can do this by either a HashTable or just a simple array if your numbers are whole numbrs and have a decent enough upper limit.
Part 2. Find duplicate frequencies.
You can just do a simple for loop to figure out which numbers are repeated more than once and then print them accordingly. This wont necessarily give them to you in order though so you can store the information in the first pass and then print it out accordingly. You can use a HashTable<Integer,ArrayList<Integer> for this. Use the key to store frequency and the ArrayList to store the numbers that fall within that frequency.
You can maintain a "max" here while inserting into our HashTable if you only want to print out only the things with most frequency.
Here is a different way to handle this. First you sort the list, then loop through and keep track of the largest numbers:
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
int n[] = { 6, 4, 6, 4, 6, 4, 1 };
List<Integer> maxNums = new ArrayList<Integer>();
int max = Integer.MIN_VALUE;
Integer lastValue = null;
int currentCount = 0;
Arrays.sort(n);
for( int i : n ){
if( lastValue == null || i != lastValue ){
if( currentCount == max ){
maxNums.add(lastValue);
}
else if( currentCount > max ){
maxNums.clear();
maxNums.add(lastValue);
max = currentCount;
}
lastValue = i;
currentCount = 1;
}
else {
currentCount++;
}
System.out.println("i=" + i + ", currentCount=" + currentCount);
}
if( currentCount == max ){
maxNums.add(lastValue);
}
else if( currentCount >= max ){
maxNums.clear();
maxNums.add(lastValue);
}
System.out.println(maxNums);
}
}
You can try it at: http://ideone.com/UbmoZ5

How can i find the positions to the three lowest integers in an array?

I how can I find the positions of the three lowest integers in an array?
I've tried to reverse it, but when I add a third number, it all goes to hell :p
Does anybody manage to pull this one off and help me? :)
EDIT: It would be nice to do it without changing or sorting the original array a.
public static int[] lowerThree(int[] a) {
int n = a.length;
if (n < 2) throw
new java.util.NoSuchElementException("a.length(" + n + ") < 2!");
int m = 0; // position for biggest
int nm = 1; // position for second biggest
if (a[1] > a[0]) { m = 1; nm = 0; }
int biggest = a[m]; // biggest value
int secondbiggest = a[nm]; // second biggest
for (int i = 2; i < n; i++) {
if (a[i] > secondbiggest) {
if (a[i] > biggest) {
nm = m;
secondbiggest = biggest;
m = i;
biggest = a[m];
}
else {
nm = i;
secondbiggest = a[nm];
}
}
} // for
return new int[] {m,nm};
}
EDIT: I've tried something here but it still doesn't work. I get wrong output + duplicates...
public static int[] lowerthree(int[] a) {
int n= a.length;
if(n < 3)
throw new IllegalArgumentException("wrong");
int m = 0;
int nm = 1;
int nnm= 2;
int smallest = a[m]; //
int secondsmallest = a[nm]; /
int thirdsmallest= a[nnm];
for(int i= 0; i< lengde; i++) {
if(a[i]< smallest) {
if(smalles< secondsmallest) {
if(secondsmallest< thirdsmallest) {
nnm= nm;
thirdsmallest= secondsmallest;
}
nm= m;
secondsmallest= smallest;
}
m= i;
smallest= a[m];
}
else if(a[i] < secondsmallest) {
if(secondsmallest< thirdsmallest) {
nnm= nm;
thirdsmallest= secondsmallest;
}
nm= i;
secondsmallest= a[nm];
}
else if(a[i]< thirdsmallest) {
nnm= i;
thirdsmallest= a[nnm];
}
}
return new int[] {m, nm, nnm};
}
Getting the top or bottom k is usually done with a partial sort. There are versions that change the original array and those that dont.
If you only want the bottom (exactly) 3 and want to get their positions, not the values, your solution might be the best fit. This is how I would change it to support the bottom three. (I have not tried to compile and run, there may be little mistakes but the genereal idea should fit)
public static int[] lowerThree(int[] a) {
if (a.length < 3) throw
new java.util.NoSuchElementException("...");
int indexSmallest = 0;
int index2ndSmallest = 0;
int index3rdSmallest = 0;
int smallest = Integer.MAX_VALUE;
int sndSmallest = Integer.MAX_VALUE;
int trdSmallest = Integer.MAX_VALUE;
for (size_t i = 0; i < a.length; ++i) {
if (a[i] < trdSmallest) {
if (a[i] < sndSmallest) {
if (a[i] < smallest) {
trdSmallest = sndSmallest;
index3rdSmallest = index2ndSmallest;
sndSmallest = smallest;
index2ndSmallest = indexSmallest;
smallest = a[i];
indexSmallest = i;
continue;
}
trdSmallest = sndSmallest;
index3rdSmallest = index2ndSmallest;
sndSmallest = a[i];
index2ndSmallest = i;
continue;
}
trdSmallest = a[i];
index3rdSmallest = i;
}
}
return new int[] {indexSmallest, index2ndSmallest, index3rdSmallest};
}
This will have the three lowest numbers, need to add some test cases..but here is the idea
int[] arr = new int[3];
arr[0] = list.get(0);
if(list.get(1) <= arr[0]){
int temp = arr[0];
arr[0] = list.get(1);
arr[1] = temp;
}
else{
arr[1] = list.get(1);
}
if(list.get(2) < arr[1]){
if(list.get(2) < arr[0]){
arr[2] = arr[1];
arr[1] = arr[0];
arr[0] = list.get(2);
}
else{
arr[2] = arr[1];
arr[1] = list.get(2);
}
}else{
arr[2] = list.get(2);
}
for(int integer = 3 ; integer < list.size() ; integer++){
if(list.get(integer) < arr[0]){
int temp = arr[0];
arr[0] = list.get(integer);
arr[2] = arr[1];
arr[1] = temp;
}
else if(list.get(integer) < arr[1]){
int temp = arr[1];
arr[1] = list.get(integer);
arr[2] = temp;
}
else if(list.get(integer) <= arr[2]){
arr[2] = list.get(integer);
}
}
I'd store the lowest elements in a LinkedList, so it is not fixed on the lowest 3 elements. What do you think?
public static int[] lowest(int[] arr, int n) {
LinkedList<Integer> res = new LinkedList();
for(int i = 0; i < arr.length; i++) {
boolean added = false;
//iterate over all elements in the which are of interest (n first)
for(int j = 0; !added && j < n && j < res.size(); j++) {
if(arr[i] < res.get(j)) {
res.add(j, i); //the element is less than the element currently considered
//one of the lowest n, so insert it
added = true; //help me get out of the loop
}
}
//Still room in the list, so let's append it
if(!added && res.size() < n) {
res.add(i);
}
}
//copy first n indices to result array
int[] r = new int[n];
for(int i = 0; i < n && i < res.size(); i++) {
r[i] = res.get(i);
}
return r;
}
In simple words, you need to compare every new element with the maximum of the three you have at hand, and swap them if needed (and if you swap, max of the three has to be recalculated).
I would use 2 arrays of size 3 each:
arrValues = [aV1 aV2 aV3] (reals)
arrPointers = [aP1 aP2 aP3] (integers)
and a 64 bit integer type, call it maxPointer.
I will outline the algorithm logic, since I am not familiar with Java:
Set arrValues = array[0] array[1] array[2] (three first elements of your array)
Set arrPointers = [0 1 2] (or [1 2 3] if your array starts from 1)
Iterate over the remaining elements. In each loop:
Compare the Element scanned in this iteration with arrValues[maxPointer]
If Element <= arrValues[maxPointer],
remove the maxPointer element,
find the new max element and reset the maxPointer
Else
scan next element
End If
Loop
At termination, arrPointers should have the positions of the three smallest elements.
I hope this helps?
There is an easy way to find the positions of three lowest number in an Array
Example :
int[] arr={3,5,1,2,9,7};
int[] position=new int[arr.length];
for(int i=0;i<arr.length;i++)
{
position[i]=i;
}
for(int i=0;i<arr.length;i++)
{
for(int j=i+1;j<arr.length;j++)
{
if(arr[i]>arr[j]){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
int tem=position[i];
position[i]=position[j];
position[j]=tem;
}
}
}
System.out.println("Lowest numbers in ascending order");
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
System.out.println("And their previous positions ");
for(int i=0;i<arr.length;i++)
{
System.out.println(position[i]);
}
Output
you can do it in 3 iterations.
You need two extra memory, one for location and one for value.
First iteration, you will keep the smallest value in one extra memory and its location in the second. As you are iterating, you compare every value in the slot with the value slot you keep in the memory, if the item you are visiting is smaller than what you have in your extra value slot, you replace the value as well as the location.
At the end of your first iteration, you will find the smallest element and its corresponding location.
You do the same for second and third smallest.

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