Explain Codes LogoExplain Codes Logo

Sort an array in Java

java
sorting-algorithms
array-sorting
java-sorting
Nikita BarsukovbyNikita Barsukov·Dec 3, 2024
TLDR

Simplicity at its finest. To sort an array of primitives such as int[], we use Arrays.sort():

Arrays.sort(arr); // arr is your int array which is about to get sorted!

Objects like String[]? Same method, same result:

Arrays.sort(arr); // arr is your String array. I sort everything!

Want your custom order? Craft a Comparator:

Arrays.sort(arr, (a, b) -> a - b); // For Integer[], sorts in ascending. Reverse the operation for a twist!

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?

Random rnd = new Random(); int[] arr = new int[10]; // A perfect 10! for(int i = 0; i < arr.length; i++) { arr[i] = rnd.nextInt(100); // Spitting out random numbers like a lottery machine! }

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.

// Example insertion sort for(int i=1; i<arr.length; i++) { int key = arr[i]; int j = i - 1; while(j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; // Patience is a virtue and so is insertion sort! }

Reverse the spell

Sorting from Z to A or in our case, from the highest number to the lowest, use a reverse for loop:

for(int i = arr.length - 1; i >= 0; i--) { System.out.print(arr[i] + " "); } System.out.println(); // Make the output pretty!

To visualize our triumph, leverage Arrays.toString():

System.out.println(Arrays.toString(arr)); // Print before sorting Arrays.sort(arr); System.out.println(Arrays.toString(arr)); // Look ma, I sorted it!

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?

// Bubble sort in action boolean swapped; do { swapped = false; for (int i = 1; i < arr.length; i++) { if (arr[i - 1] > arr[i]) { int temp = arr[i - 1]; arr[i - 1] = arr[i]; arr[i] = temp; // Swapping in action. No one sees me coming! swapped = true; } } } while (swapped); // Did we swap? Yes? Continue! No? We're done!

The next level - Advanced sorting

Use radix or counting sort for integers with a limited range, or even parallel sort. Because why not?

Arrays.parallelSort(arr); // Unleashing multi-core superpowers!

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:

Arrays.sort(arr, (a, b) -> b - a); // For Integer[], sorts in descending. Just going against the tide!

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.