File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes for loops...sorter application Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "for loops...sorter application" Watch "for loops...sorter application" New topic

for loops...sorter application

kieran pattni
Ranch Hand

Joined: Jan 19, 2004
Posts: 47
hi..i having problem understanding the flow of the for the bubble sort puts the list in the correct alphabetic order...
[ edited to preserve formatting using the [code] and [/code] UBB tags -ds ]
[ September 17, 2004: Message edited by: Dirk Schreckmann ]
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11952

if you'd put the code tags around the relavant part of your post, it'd be easier to read...


think of the two loops as pointers into a stack of cards. the outer one is where you want to put a card. you start at the beginning - you want to find the card that goes in the front of the list. after you find the right card, you can move this finger to the next spot - you now need to find the card for the second spot. once you find the second to last card and put it in place, you know the last card is where it needs to be, so you can quit. that's the outer loop.

the inner loop is the one that keeps track of the cards you're checking to put into the front spot. you don't have to check anything BEFORE your first finger, 'cause you know those are already sorted. so you can start looking at the first card AFTER where your first finger (outer loop) is pointing. that's why it's j = i+1...

anyway, for each of these cards, you look to see if it goes before the one you're first finger is pointing to. if so, you swap the two cards. you may make several swaps as your second finger moves through the list, but when it gets to the end, you know you have one card in the right position.

it's usually not very efficient for large projects, but it can be fast if the data is mostly sorted already. it works something like this (assume we want smallest to largest:


[ September 16, 2004: Message edited by: fred rosenberger - freakin' spaces]
[ September 16, 2004: Message edited by: fred rosenberger ]

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
kieran pattni,

When posting code, please be sure to surround the code with the [code] and [/code] UBB Tags. This will help to preserve the formatting of the code, thus making it easier to read and understand.

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link:
subject: for loops...sorter application
It's not a secret anymore!