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]?
            Asked
            
        
        
            Active
            
        
            Viewed 1,541 times
        
    -1
            
            
         
    
    
        thegrinner
        
- 11,546
- 5
- 41
- 64
 
    
    
        Rocky Sinha
        
- 93
- 2
- 10
- 
                    1[What have you tried?](http://whathaveyoutried.com) And are you sure you need to optimize this? Have you timed your code? – thegrinner Sep 18 '12 at 17:47
- 
                    5You are not happy with Arrays.sort or Collections.sort (in case that array is in a java collection)? – Vikdor Sep 18 '12 at 17:47
- 
                    1http://stackoverflow.com/questions/8938235/java-sort-an-array?rq=1 .. not a very good question either, but it provides code on how to sort an array – Sep 18 '12 at 17:58
2 Answers
6
            
            
        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.
 
    
    
        Kumar Vivek Mitra
        
- 33,294
- 6
- 48
- 75
0
            
            
        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.
 
    
    
        sabre_raider
        
- 138
- 2
- 
                    1(Why would the Java built-in sort implementations not use these "advanced sorting techniques"? Manually writing a quick/merge/comb sort implementation is an interesting exercise, but often nothing more.) – Sep 18 '12 at 17:55
- 
                    Afaik java uses QuickSort. I just tried to answer the original question "what is the optimized way" and in my opinion the optimized way is using QuickSort or MergeSort - no matter who implemented it. – sabre_raider Sep 19 '12 at 22:43