# simple array processing(apparently!)

• 02-05-2011, 12:26 PM
stateofyouboi
simple array processing(apparently!)
any help at all with this would be great,ive spent hours googling yesterday but to no avail

int [] nums = {10,20,10,20,60,10,5,60,5,60}

1. (i)find the maximum in the array (ii)the position of where it occurs first and last
2. find 2nd largest element in array
3. find the maximum absolute difference between adjacent pairs of elements in the array
4. determine IF 2 arrays are identical
5. reverse the order of the array elements

i was able to do q1 part (i) then i havent a clue!

int highest = 0;

for (int i=0; i<nums.length; i++) {
if(nums[i] > highest)
highest = nums[i];
}
System.out.println(highest);

when it mentions determine if 2 arrays are identical i think it could be referring to my last exercise sheet which had the same array, im not sure. The lecturer will be going through this with us next week but i need all the help i can get so im trying to stay ahead of things if you know what i mean :) even help with one or two might point me int he right direction!
• 02-05-2011, 01:12 PM
j2me64
your 1. requirement is ok. for the 2. reguirement the implementation would be very easy if your array is already sorted, so before you assign the highest you could get the value inside highest and this value will be the 2nd largest. for sorting make a call to Arrays.sort(nums). the 3. can be also be implemented in simple for-loop. for 4. the question is, if you want to list all identical arrays. and for the 5. i would write a comparator the sort the ints in reverse order. for a ascending order the returned value is calculated by firstInt.compareTo(secondInt) and for a descending order a simply secondInt.compareTo(firstInt) can be used. but watch out: before you can call the compareTo you must convert your int to the class Integer. perhaps somebody can suggest an easier way.
• 02-05-2011, 06:17 PM
pbrockway2
The code you posted found the highest value in the array. For part (ii) what you need is another variable, say highestNdx, that "remembers" the index where you set or updated the highest

Code:

```int highest = 0; int highestNdx = 0; for (int i=0; i<nums.length; i++) { if(nums[i] > highest)     highest = nums[i];     highestNdx = ??? }```
-----------------------------

If you can't use Arrays.sort() then the code to find the second highest is much the same as the code to find the highest value. All you need is a slightly more complicated condition for the if statement which expresses the condition "if current num is bigger than highest AND i is not equal to highestNdx" - basically you do search for the highest again ignoring the index position that you found initially.

(With some ingenuity you could combine both searches into one for loop, but I don't think that's the intent here.)