File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes array read from left to right or right to left? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "array read from left to right or right to left?" Watch "array read from left to right or right to left?" New topic
Author

array read from left to right or right to left?

Michael Baca
Greenhorn

Joined: May 27, 2004
Posts: 17
I'm working my way though the sun.java.com trails and have a question that is just not making sense to me. I should know this, but alas I do not.

In the first loop how is the array being read? (see full source below)


I mean is it being read starting at index 0 then 1,2,3 etc.. That
to me seems the most logical path to take. But at the end of this first loop:

--i >= 0;

Is '0' index 0 or is it just null as in end of indices? If it's Index
0 then it would be reading them from right to left.. I'm just trying
to figure out how the array is being read here. It's a rather pointless question I know, but I just want to know anyway. To 'settle my brain' let's say.


[ May 29, 2004: Message edited by: Michael Baca ]
Michael Baca
Greenhorn

Joined: May 27, 2004
Posts: 17
OK so it's reading from 0 to 9.. My bad. I guess I should have payed more attention. One more question, would it be better to use null or 0?
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
would it be better to use null or 0?

I'm not sure what you mean. In what context? Note that you cannot compare a primitive value to null.

Also, note that a good lesson to pull away from your above misunderstanding is, "Don't write code like this!" Always strive to write clear code that communicates well to the humans that read it.

In my opinion, while for (int i = arrayOfInts.length; --i >= 0; ) isn't a horrible example of unclear code, it breaks from the typical use of a for-loop, since the value assigned in the initialization section isn't the actual initial index to be used to access a component in the array, or to be used to determine whether to execute another iteration.
[ May 29, 2004: Message edited by: Dirk Schreckmann ]

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Michael]: OK so it's reading from 0 to 9.. My bad. I guess I should have payed more attention.

Errr, there are two variables being used here, i and j. One is going forward, the other is going backward. You need to study the behavior of both.

[Michael]: would it be better to use null or 0?

I agree with Dirk here. There's really no way to interchange 0 with null in Java. Perhaps you're thinking of C or some other language? If you're dealing with numbers, use 0; if you're dealing with objects, use null. In this case you're dealing with numbers, of datatype int. As an excercise, try to use null instead. You'll probably find that the compiler won't let you. (Either that, or you'll change the logic so it no longer does what the original code did. Try not to do that. )

[Dirk]: it breaks from the typical use of a for-loop

Yes it does. However sometimes there's good reason to do so. This code seems to implement a bubble sort, and it wouldn't work correctly if the outer loop went from 0 to 9. Got to be the other way around, or the numbers won't get sorted completely.

Hmmm, actually I don't think there's any use to having i == 0 either, since there's nothing the inner loop can do in that case. We might as well make the outer loop condition (i > 0) rather than (i >= 0). But that's a minor point; doesn't change the results.
[ May 30, 2004: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
[Dirk]: it breaks from the typical use of a for-loop

[Jim]: Yes it does. However sometimes there's good reason to do so. This code seems to implement a bubble sort, and it wouldn't work correctly if the outer loop went from 0 to 9. Got to be the other way around, or the numbers won't get sorted completely.

[Dirk]:To be clear, my comment didn't concern which direction the array is traversed. I railed against --i >= 0; and the "false" initialization. That for-loop could easily be rewritten to more clearly follow the typcial for (initilization; test for continuance; increment/decrement) format.
[ May 30, 2004: Message edited by: Dirk Schreckmann ]
James Chegwidden
Author
Ranch Hand

Joined: Oct 06, 2002
Posts: 201
Yes, it it appears he is using a bubble sort.

I would say:

for(int pass = 1; pass < array2.length: pass++) //no of passes
for (int element = 0; element < array2.length - 1; element++) // no. of comparions.

... rest of code

Remember in most sorts the outloop controls the number of passes and the inner loop controls the number of comparions.

Dirk and Jim, you should teach this stuff-like me!! You seem to give good ideas

JC


Author and Instructor, my book
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Dirk]: my comment didn't concern which direction the array is traversed

Mmm, I see that now. Guess I posted without reading closely enough. Sorry about that. I agree, the i-- in the condition is probably a bad idea.

James: yes, it's possible to rewrite it so both loops are going forward. But the version you show seems to be doing about twice as many comparisons as necessary, isn't it? The inner loop doesn't need to traverse the whole array each time, does it? The first time the outer loop completes, the last element in the array is guaranteed to be in the correct position; the second time, the last two are guaranteed to be in position; etc. How about:

[James]: Dirk and Jim, you should teach this stuff-like me!! You seem to give good ideas

Thanks. I've taught inro Java courses a few times. My main problem was that I was always too easily distracted by whoever asked the most interesting question - forgetting that the other students had no idea what we were talking about.
James Chegwidden
Author
Ranch Hand

Joined: Oct 06, 2002
Posts: 201
A bubble sort- the smallest element is bubbled from the unsorted sublist and moved to the sorted sublist.

Also, typically sorts are programmed from left to right not right to left. Thus, I would not use --.

To me, with your code you would no longer have a bubble sort- but an insertion sort where it follows the same pattern as the bubble sort but then inserts the first element from the unsorted list into its proper position relative to the rest of the data in the sorted list.

Also, remember with this small data set- it really does not matter (efficiency) which sort is implemented: bubble, insertion, selection, quicksort, etc.

Jim, I sometimes get hung up with student that ask "advanced" questions. Usually I either:
1. wait until the end of class to answer the question.
2. tell them we will answer that question at a later date.
3. tell them after class.

Usually advanced questions fall under 3 most of the time.

James C.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
A bubble sort- the smallest element is bubbled from the unsorted sublist and moved to the sorted sublist.

...

To me, with your code you would no longer have a bubble sort- but an insertion sort where it follows the same pattern as the bubble sort but then inserts the first element from the unsorted list into its proper position relative to the rest of the data in the sorted list.


In this case, the largest element is bubbled from the unsorted sublist to the sorted sublist, which is kept at the end of the original list. (Which is why we don't need to loop through that part of the list on subsequent iterations; it's already sorted.) Just like the original code, really, except for the introduction of the intermediate variable numComparisons, which was unnecessary except maybe for clarity. And I end the outer loop on eiteration earlier, as discussed.

Also, typically sorts are programmed from left to right not right to left. Thus, I would not use --.

Not sure what this is in reference to - the original code shown by Michael? Regardless, googling on "bubble sort algorithm" given plenty of examples that use -- to implement a bubble sort, so I disagree about what's "typical".

Also, remember with this small data set- it really does not matter (efficiency) which sort is implemented: bubble, insertion, selection, quicksort, etc.

Agreed, so far as it goes. This particular sample set is small, but who's to say there won't be larger ones in the future? Of course in the real world we'd use another algorithm anyway; this is presumably just for learning purposes. But IMO that doesn't mean we should be completely oblivious to performance concerns. The original code correctly omitted looping through the already-sorted part fo the list; getting rid of that optimization seems a step backward, IMO.
[ May 30, 2004: Message edited by: Jim Yingst ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: array read from left to right or right to left?
 
Similar Threads
Can someone please explain the following code to me...
Comparing values
Sorting an 2D object array
Problem in array length
need help sorting Integer objects