简体   繁体   中英

Optimal way to sort an array

I have an array in the form [A,B,B,A,A] . What is the optimized way to sort the array so I get [A,A,A,B,B] ?

When you have the the Power bring it to good use... Why reinvent the wheel ???

Use Arrays.sort() to sort the Array.

- If what you hold in the Array is some kind of object and it needs to be sorted in More than One way.... then first convert it in to a ArrayList (or List) using Arrays.asList(array)

Eg:

Song[] dog = new Song[10];
 ArrayList<Song> list = new ArrayList<Song>(Arrays.asList(arr));

Then use java.util.Comparator Interface, to sort the Object on basis of more than one attribute.

Eg: Class Song can be sorted on the basis of its track title or Singer and more using Comparator Interface.

- Using Collections are lot more flexible than Array .

Use some kind of QuickSort or MergeSort if you want to implement fast sorting on your own.

Otherwise use the built in java sort functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM