Copyright

How to Sort an Array in Java

An error occurred trying to load this video.

Try refreshing the page, or contact customer support.

Coming up next: Java: Multidimensional Arrays

You're on a roll. Keep up the good work!

Take Quiz Watch Next Lesson
 Replay
Your next lesson will play in 10 seconds
  • 0:04 Arrays
  • 0:36 Sorting
  • 1:43 Java.Util.Arrays
  • 3:53 Lesson Summary
Save Save Save

Want to watch this again later?

Log in or sign up to add this lesson to a Custom Course.

Log in or Sign up

Timeline
Autoplay
Autoplay
Speed Speed

Recommended Lessons and Courses for You

Lesson Transcript
Instructor: Sebastian Garces

Sebastian has taught programming and computational thinking for University students and has Master's degree in Computer and Information Technology

In this lesson, we will learn how sorting works in Java, the importance of the sorting algorithms and the variables to consider when using sorting to manipulate arrays.

Arrays

You've probably worked with arrays before, those created by adding a couple of brackets [] to a variable in the code that will let us store multiple items in list kind of way. You can see this in the code below:

int [] array = {1,2,3,4,5};
int array [] = {1,2,3,4,5};

Both these are valid ways to have arrays in Java.

Now we're going to explore a new library, java.util.Arrays, that will give us access to more methods to extend what we can do with arrays. But before we do that, we're going to go over how to sort an array manually since it's one of the most common operations done on arrays.

Sorting

Sorting is one of the most common operations done on arrays. We're going to perform a manual sort so we can fully understand what this operation does with our information.

There are multiple sorting algorithms that we can use depending on our needs. This determines how sorted the data is in an array or the number of unique values you can have on it. Let's look at an example of an insertion-sort. This sorting algorithm is a basic one, very similar to what you do when shuffling the cards in your hand. It will take one item in the array and find the position it should go in according to the sorting criteria. Let's say we have a random array and we want to sort it in ascending order. You can see here:


public class InsertSort {
  public static void main (String [] args) {
   int [] array = {45,12,85,32,89,39,69,44,42,1,6,8};
   int temp;
   for (int i = 1; i < array.length; i++) {
    for (int j = i; j > 0; j--) {
     if (array[j] < array [j - 1]) {
      temp = array[j];
      array[j] = array[j - 1];
      array[j - 1] = temp;
     }
    }
   }
   for (int i = 0; i < array.length; i++) {
     System.out.println(array[i]);
   }
  }
}


This code will print item by item in the array in ascending order by finding the right spot for each item without having to go through all of the array twice with every single item. It just compares from left to right checking if the number before the one to be analyzed is less, then it switches positions and repeats that process with every item in the array.

There are multiple sorting algorithms that can be used, but this one is simple to remember and quite efficient for its low complexity.

java.util.Arrays

Now it's time to do some more exploring into arrays. java.util.Arrays is a library included in Java programming language that will let us perform more operations on arrays, giving us access to more than 100 methods. We won't go through all of them in this lesson, but we will cover the most important ones.

In the java.util.Arrays library we've got several sort methods for several different types of arrays. In this case, we'll work with integers but the principle remains the same for different data types. We're going to use a sort method which will save us time by not requiring us to manually create the loops for sorting but do it automatically. Let's see how this works with the code appearing below:


import java.util.Arrays;
public class Sorting {
  public static void main (String [] args) {
   int [] array = {45,12,85,32,89,39,69,44,42,1,6,8};
   Arrays.sort(array);
   for (int i = 0; i < array.length; i++) {
   System.out.println(array[i]);
   };
  }
}


So, as you can see, we get the same array in ascending order without having to create the sorting algorithm. This method not only is faster when coding but also when sorting, since it implements an advanced sorting technique called Dual-Pivot QuickSort, which works more efficiently overall.

Let's take a look at an example of range sorting. If for some reason we needed to sort only a range of the array, we can still use the same method. We just need to specify the range, like this code appearing below:


To unlock this lesson you must be a Study.com Member.
Create your account

Register to view this lesson

Are you a student or a teacher?

Unlock Your Education

See for yourself why 30 million people use Study.com

Become a Study.com member and start learning now.
Become a Member  Back
What teachers are saying about Study.com
Try it risk-free for 30 days

Earning College Credit

Did you know… We have over 200 college courses that prepare you to earn credit by exam that is accepted by over 1,500 colleges and universities. You can test out of the first two years of college and save thousands off your degree. Anyone can earn credit-by-exam regardless of age or education level.

To learn more, visit our Earning Credit Page

Transferring credit to the school of your choice

Not sure what college you want to attend yet? Study.com has thousands of articles about every imaginable degree, area of study and career path that can help you find the school that's right for you.

Create an account to start this course today
Try it risk-free for 30 days!
Create an account
Support