Sort an array in Java
Simplicity at its finest. To sort an array of primitives such as int[]
, we use Arrays.sort()
:
Objects like String[]
? Same method, same result:
Want your custom order? Craft a Comparator
:
Arrays.sort()
is like the Flash—fast & efficient. Uses quick sort for primitives, tim sort for objects, achieves in typically O(n log(n)).
Roll the dice - Random array initialization
To initialize our array with random values, we call upon the Random
class. You didn't see that coming, did you?
Sorting algorithms: Efficiency is key
For sorting larger arrays, consider quick sort or merge sort. They're the formula one cars of sorting! For specific use-cases like nearly sorted arrays, insertion sort is your friend in need.
Reverse the spell
Sorting from Z to A or in our case, from the highest number to the lowest, use a reverse for loop:
To visualize our triumph, leverage Arrays.toString()
:
Digging deeper - Understanding sorting algorithms
Getting our hands dirty by understanding bubble sort:
- Compare neighbors and swap if they're in the wrong neighborhood.
- Keep the cycle going until everyone finds their rightful place. No more swaps needed!
Getting sorted - manually!
Implementing sorting algorithms manually might seem old school, but it's a great exercise. Plus, who doesn't love a good exercise?
The next level - Advanced sorting
Use radix or counting sort for integers with a limited range, or even parallel sort. Because why not?
Choosing the right algorithm = Faster sorting = Happy developers!
Keep an eye on - Common pitfalls
When sorting, "primitive" vs "object" types matter more than you think. Using a custom comparator with primitives
is like building a house on sand — it just doesn't work!
Sorting - Ascending or descending, you choose!
Sorting in descending order is as easy as 1, 2, 3! Just tweak the comparator:
Stability on ground and in sorting
Arrays.sort()
is stable for object arrays — equal elements maintain their original order. This matters when you want to sort objects with multiple fields.
Was this article helpful?