• Post Reply Bookmark Topic Watch Topic
  • New Topic

sorting backwards with Arrays.sort()  RSS feed

 
Aron Jhed Amiscosa
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.
 
Sean Clark
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
 
Wouter Oet
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.
 
Garrett Rowe
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:

 
Suhas Bilaye
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
 
Sha Jar
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!