Skip Top Navigation Bar

Sorting Arrays with Arrays.sort()

Java provides built-in methods for sorting arrays. Instead of writing your own sorting algorithm, you can use the Arrays.sort() method to arrange the elements of an array in ascending order.

Using Arrays.sort() is the simplest and most common way to sort data in Java.

The sort() method rearranges the elements already stored in the array. It does not create a new array. Because the original array is modified, you do not need to assign the result to another variable.

Sorting an Array of Numbers

Pass the array to Arrays.sort(). For example:

This will give you the values in the array sorted in ascending order, or from smallest to largest:

Your Turn

  1. Predict the output and run the code to verify.
  2. Modify the array to {8, 3, 8, 1, 8, 6}. Predict the output and run the code to verify.
  3. What happens if the list is already sorted? Modify the array to {1, 2, 3, 4}. Predict the output and run the code to verify.
  4. What happens if the list is already sorted from greatest to least? Modify the array to {8, 7, 6}. Predict the output and run the code to verify.

Sorting an Array of Strings

You can also sort arrays of strings.

This will give you an array of Strings sorted in lexicographical order. Lexicographical is like alphabetical order, except uppercase letters come before the lowercase letters.

Your Turn

  1. Predict the output and run the code to verify.
  2. What happens when you have a mix of upper and lowercase letters at the start of the words? Modify the array to {"b", "B", "a", "C"}. Predict the output and run the code to verify.

Sorting Part of an Array

You can also sort a portion of an array by specifying the starting index (inclusive) and ending index (exclusive).

This will sort the middle of this array starting at index 1. The values at index 0 and 4 are unmoved.

Your Turn

  1. Predict the output and run the code to verify.
  2. Modify the code to sort the second half of the array only. Predict the output and run the code to verify.