This week's book giveaway is in the Jython/Python forum.
We're giving away four copies of Hands On Software Engineering with Python and have Brian Allbey on-line!
See this thread for details.
Win a copy of Hands On Software Engineering with Python this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Bear Bibeault
  • Knute Snortum
  • Liutauras Vilda
Sheriffs:
  • Tim Cooke
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Ron McLeod
  • Ganesh Patekar
  • salvin francis
Bartenders:
  • Tim Holloway
  • Carey Brown
  • Stephan van Hulst

sorting backwards with Arrays.sort()  RSS feed

 
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello. i just want to ask, if how can i sort an int array backwards?


the values on the array are input from user. but as example,


so i wanted to sort it inverse chronologically...

so the result i would like is

11
10
8
7
5
5
2

how can i do this now?

thanks in advance.
 
Rancher
Posts: 377
Android Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey,

You can use the method Arrays.sort(Object[] a, Comparator c) this allows you to create your own comparator to compare 2 Integers and thus create your own ordering.
For reversing the answer is very simple.

Sean
 
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or just swap them

 
Aron Jhed Amiscosa
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi there.
thanks to both of you.

you both saved me.
 
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since you got a solution already, I don't think there's any harm in giving away this code. Java's type system doesn't handle a lot of type inference, but you can do some neat tricks with what little it does offer:

 
Ranch Hand
Posts: 80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You also have a Collections.reverseOrder() static method which returns a Comparator. It can be used to sort collections or arrays in reverseOrder.
Though you have already got the solution, would like to share this as it was quite helpful to me.

Regards,
Suhas
 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can also sort the array in straight order and then afterwards read it in reverse order.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!