Subscribe
public static int[] findLargestNItems(int[] items, int findLargest) {
int[] itemsCopy = new int[items.length];
System.arraycopy(items, 0, itemsCopy, 0, items.length);
int[] largestItems = new int[findLargest];
Arrays.sort(itemsCopy);
System.arraycopy(itemsCopy, items.length - findLargest, largestItems, 0, findLargest);
return largestItems;
}
public int[] getMaxValues(int[] myArray, int numValues )
{
int[] results = new int[numValues];
int iLowestResult = 0;
int iNumresults = 0;
int iLength = myArray.length();
for (int iIndex=0; iIndex < ilength; ++iindex)br>
{
int iValue = myArray[iIndex];
if ((iNumResults < numvalues)br>
|| (iValue >= iLowestResult))
{
results[iNumResults++] = iValue;
iLowestResult = iValue;
}
}
return results;
}
>>iLowestValue in the body of the if in the event of iValue == iLowestValue. This is necessary, though because the if clause is constructed on the assumption that the result-set can contain non-unique integers. The alternative is to perform a test before that assignment to determine that iValue != iLowestValue. The assumption I've made is that, in a general case, a comparison is more computationally wasteful than an assignment.
public int[] getMaxValues(int[] myArray, int numValues )
{
SortedList results = new SortedList();
int iLength = myArray.length();
for (int iIndex=0; iIndex < ilength; ++iindex)br>
{
int iValue = myArray[iIndex];
if (results.size() < numvalues)||(ivalue> results.lowest()))
{
results.add(iValue);
}
}
return results.toArray(myArray);
}
>>
n = 5
narray = []
for i in marray:
if i > narray[n-1]:
narray[n-1] = i
for j in range(n, 0, -1):
if narray[j] > narray[j-1]:
swap (narray[j], narray[j-1])
print narray
n = 5
narray = []
for i in marray
{
if i > narray[n-1]
{
narray[n-1] = i
for j in range(n, 0, -1)
{
if narray[j] > narray[j-1]
{
swap (narray[j], narray[j-1])
}
}
}
}
print narray
for (i=0; i < m; i++) {br> if (heap.count() < n) {br> heap.add(values[i]);
} else {
if (heap.peekroot() < values[i]) {br> heap.deleteroot();
heap.add(values(i));
}
}
}
>>>
The importance of this measure can be seen in trying to decide whether an algorithm is adequate, but may just need a better implementation, or the algorithm will always be too slow on a big enough input.
posted by mr.dan at 12:59 AM on December 22, 2005