JAVA Help Please

Soldato
Joined
8 Oct 2005
Posts
4,184
Location
Midlands, UK
Hi,

I'm going through a few Java tutorials to get myself back uop to speed and for the life of me can't work this out - its a basic tutorial about sorting arrays using loops (via not importing the java.util.arrays). The code is below (see highlighted part), I can't work out why they loop for i>=2, i would have thought it would be i>=0. Have been staring at it for a while now aswell.

Thanks


Code:
public class SelectionSort {
public static void main(String[] args) {

//Create an array to test the selection sort out on
int list[] = {10,8,6,11,7};

//Store the index of the biggest item in the array
int pos;

//Output the unsorted array
System.out.println("Original list");
printArray(list);

//Loop through the array from the bottom upwards
for (int i = list.length;[COLOR=Red][B] i>=2[/B][/COLOR]; i--){

//Find the position of the largest item of i items in array list
pos = findPositionOfBiggest(list,i);

//Swap the largest item (at position pos) with the item at position i-1
swapArrayItems(list, i-1, pos);
}//end for

System.out.println("\nNew list");
printArray(list);

System.exit(0);
}//end main
 
Last edited:
Cheers for the reply.

Stuff like this will only annoy me if i don't underatand it :)

Think I underastand this now (had draw myself a diagram for each iteration lol :( ). I think the limit is set to >=2 to save an extra loop as its not needed as as when i=2 the list will look something like this (will bbe all sorted bar top 2 values):

Code:
Pos      array item:
0                   7
1            6
2                   8
3                 10
4                11
i-1 = 7
Biggest is 7 at index 0.

So i guess that limit is there to take the loop more efficient, as the loop could run the remaining times but wouldn't do anything. That's how i understand it.
 
Last edited:
Back
Top Bottom