Bubble Sort Question.

Hello,

I am a brand new to java programming (computer programming of any language period) and am starting to learn the language on my own. (I can not afford classes so I have to pick up a book and self learn). I am attempting to sort an array of numbers and can't seem to figure out why the last number in my array is not printing out. Can someone please help. Here's my code:

class sorter{

publicstaticvoid main(String args[]){

int theList[] ={10, 1, 9, 2, 8, 3, 7, 4, 6, 5};

int temp;

for(int i = 0; i < theList.length; i++){

for(int j = i + 1; j < theList.length; j++){

if(theList[i] < theList[j]){

temp = theList[i];

theList[i] = theList[j];

theList[j] = temp;

}

}

}

for(int x = 0; x < theList.length - 1; x++)

System.out.println(theList[x]);

System.out.println(theList.length-1);

}

}

The output I get is:

1

2

3

4

5

6

7

8

9

9 // repeats this number, rather than print the 10

Any assistance would be appreciated. Thanks in advance.

Vance.

[1905 byte] By [vance_massa] at [2007-10-3 3:02:16]
# 1

> for(int x = 0; x < theList.length - 1; x++)

Should be theList.length

or x <= theList.length - 1

> System.out.println(theList[x]);

> .println(theList.length-1);

>}

> /code]

> 9 // repeats this number, rather than print the 10

Yes, because System.out.println(theList.length - 1)

prints 9, and you only went through 9 of the 10 items in your array because your for loop condition was incorrect.

Brian

brian@cubik.caa at 2007-7-14 20:52:01 > top of Java-index,Java Essentials,New To Java...
# 2
Someone already answered, a blink of an eye before me...Message was edited by: Catraga
Catragaa at 2007-7-14 20:52:01 > top of Java-index,Java Essentials,New To Java...
# 3
The 9 is because list.length is 10 and so list.length - 1 is 9 and he has just asked the program to print "The length of the list less 1". In other words, the 9 at the end is independant of the loop error.
nerak99a at 2007-7-14 20:52:01 > top of Java-index,Java Essentials,New To Java...
# 4
Thank you very much for your response. vance.
vance_massa at 2007-7-14 20:52:01 > top of Java-index,Java Essentials,New To Java...
# 5

Hello there,

Welcome to JAVA!

Take a look at:

for(int i = 0; i < theList.length; i++)

You had the answer all along. :-)

Computers start to count from 0 rather than 1 like humans.

Interesting, isn't it.

Good luck!

ROuNIN

ROuNINa at 2007-7-14 20:52:01 > top of Java-index,Java Essentials,New To Java...