CodeBlanks Logo Icon CodeBlanks

Arrays.sort

Learn sorting with Arrays.sort.

Sorting with Arrays.sort

In Java, the easiest way to sort an array from smallest to largest is the Arrays.sort method. It sorts the array in place: it does not return a new array, it rearranges the elements of the existing one.

int[] scores = {78, 92, 55};
Arrays.sort(scores);
// scores is now: {55, 78, 92}

The method orders the array in ascending order. For binary search, which you will see later, the array must be sorted first.

Sorting and binary search

Some methods require a sorted array. Arrays.binarySearch is one of them: for fast lookup it requires the array to be sorted.

If the array is not sorted, binarySearch may return a wrong result; that is why you call Arrays.sort first.

int[] nums = {4, 2, 7, 1};
Arrays.sort(nums);
int i = Arrays.binarySearch(nums, 4);
// i = 2

Sorting also moves the smallest and largest values to the ends of the array, which makes further processing easier.

Practice Sort and print the scores

Sort the scores below from smallest to largest and print each one on its own line.

Starter code

Main.java
public class Main {
  public static void main(String[] args) {
    int[] scores = {78, 92, 55, 64, 88};
    // Sort the scores from smallest to largest
    // Print each score on its own line
  }
}

Sample solution

Main.java
Arrays.sort(scores);
for (int s : scores) {
  System.out.println(s);
}

Expected output

55
64
78
88
92

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens after calling Arrays.sort(scores)?

Main.java
int[] scores = {78, 92, 55};
Arrays.sort(scores);
  • It causes a compile error because Arrays.sort rejects int[]
  • The scores array stays unchanged and a sorted copy is returned
  • A new int[] is returned and scores stays the same
  • The scores array is sorted in place and returns no value Correct answer

Explanation: Arrays.sort is a void method; it sorts the array in place.

2 Fill in the blank: sort the array

Question
int[] nums = {9, 3, 7};
____;
System.out.println(nums[0]);
Answer
int[] nums = {9, 3, 7};
Arrays.sort(nums);
System.out.println(nums[0]);

Explanation: The Arrays.sort(nums) call sorts the array.

3 Match method to behavior

Term Meaning
Arrays.sort(x) Sorts the array in place
Arrays.toString(x) Converts the array to text
Arrays.binarySearch(x, v) Searches a value in a sorted array
Arrays.copyOf(x, n) Takes a copy of the array

All lessons in Beginner