Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is wrong with my generic implementation of sort method ?

 
Praveen Kumar Singh
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
For Input: [abc, abb, aaa, bbc]

Collections.sort give: [aaa, abb, abc, bbc]

I tried to implement something similar to it like this



But what i get is: [abb, aaa, abc, bbc]


Why ?.....Any Help !!

 
Paul Clapham
Sheriff
Posts: 21416
33
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's probably just a bad implementation of bubble-sort. Nothing to do with generics, I wouldn't think.

(It would be better if the method's name was "doBubbleSort" rather than "doBubbleShort" but that isn't the source of your problem.)
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Think about the scope of your inner loop.

Because you're looping from the start to finish, at the end of one iteration you've got the last element in the right place. So the next iteration you need to move across all elements except the last one. But instead, you're moving across all but the first.
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you change your method definition to:
Then you don't need to cast. Also oneSwap is never used.
 
Rob Spoor
Sheriff
Pie
Posts: 20667
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wouter Oet wrote:If you change your method definition to:
Then you don't need to cast. Also oneSwap is never used.

Make that Without the ? super part you couldn't sort a List<java.sql.Timestamp>, as Timestamp extends java.util.Date and therefore implements Comparable<Date> - not Comparable<Timestamp>.
 
Praveen Kumar Singh
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Paul and Matthew
Its end up in wrong implementation only !
I almost presume that error is in 'generic' logic only
Final code



Thanks Wouter
Its works very well
I definitely need more study on Generics !

Thanks Rob
Look like you are an expert on generics

 
Rob Spoor
Sheriff
Pie
Posts: 20667
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Expert, no. I am somewhat experienced though, even though I didn't switch from Java 1.4 to Java 5.0 for the first year or so.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic