06-21-2011, 03:56 AM
(06-20-2011, 10:46 PM)Koopaul Wrote: Yeah I have a Java programming online course, I've been doing decent but now we're at Arrays and I'm starting to get confused.
Anyway I need help figuring out the value of the num array with this program. I think I have an idea but I'm not sure. Take a look.
I tried to provide the answer stepwise, such that you can try and figure out the rest yourself after a certain step, or go to the next one if you are stuck.
The 'thumb' and 'finger' metaphores I use below are what I've been taught with, and correspond to how you could do it on paper (which usually helps with these kind of problems).
Code:
// creation of an array with some initial values.
// The i'th value is accessed using num[i] starting at 0, so num[2] is currently 10
int [] num= {20,50,10,70,40,80,30,90,60};
int t=0;
// place the thumb on each position in the array, 'from left to right'
for (int i=0; i<num.length; i++) {
// go with the finger through the rest of the array
for (int j=i+1; j<num.length; j++) {
// whenever the value at the finger is less than the value at the thumb, do something
if (num[i]>num[j]) {
t=num[i];
num[i]=num[j];
num[j]=t;
}
}
}
Once you know what 'do something' does, the next step is figuring out what it does to the array when used in the program above.