rewrote getMaxIndexes() to not choke if all the elements are less
than 0, and minimized object creation (at the expense of going through the array almost twice). git-svn-id: https://samskivert.googlecode.com/svn/trunk@805 6335cc39-0255-0410-8fd6-9bcaacd3b74c
This commit is contained in:
@@ -1,5 +1,5 @@
|
|||||||
//
|
//
|
||||||
// $Id: ArrayUtil.java,v 1.7 2002/08/09 23:33:49 shaper Exp $
|
// $Id: ArrayUtil.java,v 1.8 2002/08/10 01:39:44 ray Exp $
|
||||||
//
|
//
|
||||||
// samskivert library - useful routines for java programs
|
// samskivert library - useful routines for java programs
|
||||||
// Copyright (C) 2001 Walter Korman
|
// Copyright (C) 2001 Walter Korman
|
||||||
@@ -36,25 +36,33 @@ public class ArrayUtil
|
|||||||
*/
|
*/
|
||||||
public static int[] getMaxIndexes (int[] values)
|
public static int[] getMaxIndexes (int[] values)
|
||||||
{
|
{
|
||||||
// get the indices with the maximum values
|
int max = Integer.MIN_VALUE;
|
||||||
ArrayList list = new ArrayList();
|
int num = 0;
|
||||||
int max = 0;
|
|
||||||
for (int ii = 0; ii < values.length; ii++) {
|
for (int ii=0; ii < values.length; ii++) {
|
||||||
if (values[ii] == max) {
|
if (values[ii] < max) {
|
||||||
list.add(new Integer(ii));
|
// common case- stop checking things..
|
||||||
|
continue;
|
||||||
|
|
||||||
} else if (values[ii] > max) {
|
} else if (values[ii] > max) {
|
||||||
list.clear();
|
// new max
|
||||||
max = values[ii];
|
max = values[ii];
|
||||||
list.add(new Integer(ii));
|
num = 1;
|
||||||
|
|
||||||
|
} else {
|
||||||
|
// another sighting of max
|
||||||
|
num++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// convert the list to an array
|
// now find the indexes that have max
|
||||||
int size = list.size();
|
int[] maxes = new int[num];
|
||||||
int[] maxes = new int[size];
|
for (int ii=0, pos=0; (ii < values.length) && (pos < num); ii++) {
|
||||||
for (int ii = 0; ii < size; ii++) {
|
if (values[ii] == max) {
|
||||||
maxes[ii] = ((Integer)list.get(ii)).intValue();
|
maxes[pos++] = ii;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return maxes;
|
return maxes;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user