USB
USB

Reputation: 6139

How to find i maximum values from a file

I am having a file content like this

id  value
1   56
2   5
3   90
4   12
5   234
6   90

I am trying to find max value from the file. for eg: i=2 Then my result should be 234,90.I should be able to return 2 maximum values.

How to do this basically max can be identified by

if (value < min) {
 min = value;
}
if (value > max) {
 max = value;
}

Along with this loop am I able to get 4 max values?

Upvotes: 0

Views: 127

Answers (7)

Rohit Goyal
Rohit Goyal

Reputation: 550

Try this, hope this helps

 import java.util.*;

    public class TestNumber {

        public static void main(String args[]) {

            int[] ints = { 2, 56, 5, 90, 12, 234, 90 };
            Integer i = 3;
            getMaxValues(ints, i);
        }

        private static void getMaxValues(int[] ints, Integer i) {
            int maxRange = i;

            List<Integer> intList = new ArrayList<Integer>();
            for (int index = 0; index < ints.length; index++) {
                intList.add(ints[index]);
            }
            Collections.sort(intList);

            System.out.println("The maximum requested numbers are :");
            if (intList.size() >= maxRange) {
                for (int j = intList.size() - 1; maxRange > 0; j--) {
                    maxRange--;
                    System.out.println(intList.get(j));
                }
            }

        }
    }

Upvotes: 0

bcorso
bcorso

Reputation: 47128

A couple ways to solve your problem with the pros and cons:

description          |           pros          |         cons
------------------------------------------------------------------------------
Collections.sort     |  simple                 | inefficient O(nlogn)
selection algorithm  |  efficient O(n)         | implement from scratch, not sorted
PriorityQueue        |  simple                 | inefficient O(nlogn)
heap (bottom up)     |  efficient O(n + klogn) | implement from scratch
for-loop             |  efficient O(n), simple | hardcoded for k = 2
bubble sort          |  efficient if k << n    | O(kn) --> O(n^2) if k~n 

Here is an implementation of the for-loop method which will work if you only need a fixed k of 2.

public int[] largestTwo(int[] A){
    int[] largest = new {A[0], A[0]};  
    for(int i = 0; i < A.length; i++) {
        if(A[i] >= largest[0]){  
            largest[1] = largest[0];  
            largest[0] = A[i];  
        }else if(A[i] > largest[1]){  
            largest[1] = A[i];
        }
    }
    return largest;
}

Upvotes: 0

Instead completely ordering the elements, you can fill a priority queue and extract its root twice:

public static int[] minmax(File f)
{
    int [] res = {-1,-1};
    try {
        Scanner scan = new Scanner(f);
        scan.nextLine();
        PriorityQueue<Integer> values = new PriorityQueue(10, new Comparator<Integer>() {

            @Override
            public int compare(Integer o1, Integer o2) {
                return o2.compareTo(o1);
            }
        });
        while(scan.hasNextInt())
        {
            int id = scan.nextInt();
            if(!scan.hasNextInt()) continue;
            int val = scan.nextInt();
            values.add(val);
        }
        scan.close();
        res[0] = values.poll();
        res[1] = values.poll();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Test2.class.getName()).log(Level.SEVERE, null, ex);
    }
    return res;
}

The idea of this is to build a heap in O(n) but, as @bcorso has pointed, Java's PriorityQueue implementation does not provide that build time complexity.

Upvotes: 0

Ambrish
Ambrish

Reputation: 3677

If you are looking to find top K element from the array then there are few ways to do it:

  1. Implement http://en.wikipedia.org/wiki/Selection_algorithm.

  2. You can also explore TreeSet.

Sample code:

package impatient;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;

public class Test1 {
    public static void main(String[] args) {
        Test1 test1 = new Test1();
        List<Integer> list = new ArrayList<Integer>();
        list.add(56);
        list.add(5);
        list.add(90);
        list.add(12);
        list.add(234);
        list.add(90);
        test1.findTopN(list, 2);
        test1.findTopN(list, 4);
    }

    private void findTopN(List<Integer> list, int n) {
        TreeSet<Integer> sortedList = new TreeSet<Integer>(new Comparator<Integer>() {
            @Override
            public int compare(Integer a, Integer b) {
                return a > b ? 1 : -1;
            }
        });

        sortedList.addAll(list);

        Iterator<Integer> it = sortedList.descendingIterator();

        int index = 0;
        System.out.print("Top " + n + " elements : ");
        while (it.hasNext() && index < n) {
            System.out.print(it.next() + ", ");
            index++;
        }
        System.out.println();
    }
}

Output:

Top 2 elements : 234, 90, 
Top 4 elements : 234, 90, 90, 56, 

Upvotes: 0

Engineer
Engineer

Reputation: 1434

public void findHighest(int[] array){  
        int highest = array[0];  
        int secondHighest = array[0];  

            for(int i=0;i<array.length;i++) {  


            if(array[i] > highest){  

                secondHighest = highest;  
                highest = array[i];  



             }  
        } // end for  
    } // end method  

Upvotes: 0

LMK
LMK

Reputation: 2962

Try this

import java.util.*;

public class Test {

    public static void main(String ar[])
    {
        ArrayList<Integer> i = new ArrayList<Integer>();

        i.add(200);
        i.add(203);
        i.add(250);
        i.add(270);
        i.add(20);
        i.add(300);
        i.add(60);
        i.add(10);

        System.out.println(i);
        Collections.sort(i);
        System.out.println(i);

        int someValue = 3;
        if(i.size()>=someValue)
        {
            for(int j = i.size() - 1; someValue>0; j--)
            {
                someValue--;
                System.out.println(i.get(j));
            }
        }
    }
}

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201477

Here is one way you can get count maximum values from an array,

public static int[] getMaxValues(int count, int... values) {
    int[] v = values.clone();
    Arrays.sort(v);
    return Arrays.copyOfRange(v, v.length - count, v.length);
}

public static void main(String[] args) {
    System.out.println(Arrays.toString(getMaxValues(2, 56, 5, 90, 12, 234, 90)));
}

Output is (the requested)

[90, 234]

Upvotes: 2

Related Questions