Hey guys its Teja here, so In this tutorial we will be learning about Sorting techinque in Java. Wait, sorting in java? What does that mean?
Oops, my bad. I’m sorry. I didn’t include the word ‘Array’ anywhere in the above sentence, so it didn’t make sense.

 

Alright let me give it another try. Ready….. go

Hey Guys! Its Teja here and in this tutorial I will be teaching you about Sorting Array elements in Java.
Well, that’s a perfect Intro. Now since I got the intro right, let’s get started 🙂

 

Sorting Arrays in Java Programming

Okay, I must assume that since you are reading this article, you must have already been familiar about ‘Arrays’ . Like, I hope you all know how elements are stored in the array, how they are inputted, and other basic stuff like that.
Wait, am I panicking anyone? Well, there is nothing to worry even if you have no basic idea about Arrays, you can always find a way when we are with you. I will be providing you a video, as well as another article which was posted on one of our other blogs, which explains you the basics of Arrays in Java.


Here is the article which deals with Array basics in Java Programming : click here to read
And here is a video tutorial on the Basics of Arrays in Java : 

 

Sorting Arrays in Java – Complete Explanation

So, there are two types of Sorting techniques in Java Programming. They are

1. Selection Sort

2. Bubble Sort

Selection Sorting

 

Here is a program to demonstrate the Selection Sorting.

 

class SelectionSort  //Line 1 – Declaring class named ‘SelectionSort’
//Line 2 – Class starts here
static void test() //Line 3 – declaring method ‘test’
//Line 4 – method starts here
int[] arr = {2,8,15,1,24,13,4}; //Line 5 – declaring integer datatype array ‘arr’ and storing some elements
int n = 7; //Line 5 – declaring an integer variable ‘n’ and storing the number of elements present in the array(you can do this by  (arr.length+1)
for(int i = 1;i<=n;i++) //Line 6 – starting the outer for loop which iterates from i=1 to i<= number of array elements present (n)
//Line 7 – for loop starts here
for(int j = 0;j<(n-1);j++) //Line 8 – inner for loop that runs from j = 0 to j<(n-1)
//Line 9 – inner for loop starts here
int k = j+1; //Line 10 – declaring ‘k’ as integer type, which stores (j+1)
int a = arr[j]; //Line 11 – declaring variable ‘a’ as int type. It stores the element present at the ‘j’ th index of the array ‘arr’
int b = arr[k]; //Line 12 – Similarly, stores the element present at the ‘k’ th index of the array ‘arr’
if(b<a) //Line 13 – checking if b<a using an if-block
//Line 14 – if-block starts here
arr[j] = b; //Line 15 – swapping the element at ‘j’ th index with the value ‘b’
arr[k] = a; //Line 16 – swapping the element at ‘k’ th index with the value ‘a’
//Line 17 – End of if-block
//Line 18 – End of inner for loop
//Line 19 – End of outer for loop
for(int d = 0;d<n;d++)  //Line 20 – for loop to display the resultant array
System.out.print(arr[d]+” “); //Line 21 – Print statement to print out the element at “d” th index of the resultant array
//Line 22 – End of method test

//Line 1 – End of the class

Explanation of the Above Program

First off, for this program we initialized an array ‘arr’ as Integer data type. This array is just an example, and we are considering it for understanding the Selection sort algorithm. Consider some sample values 2,8,15,1,24,13,4 as the elements of this array. Now we will try to sort these elements in ascending order using the selection sort technique.

First off, we will store the number of elements of this array(we know it is,7) in a variable ‘n’ of Integer type. If you don’t know the number of elements present in the array, you can use this, int n = arr.length+1 which will result the total number of elements in the array.
We declared the variables i and j for the sake of outer and inner for loops respectively. 

Now, let’s discuss the alogrithm of Selection sort. Before that, let me write down the elements in the array along with their index numbers.
Index Numbers : 
       0   ,   1    ,    2   ,   3   ,   4     ,    5   ,    6

Elements :                  2   ,   8   ,   15   ,   1   ,   24   ,   13   ,   4

 

Firstly, we take the element at the 0th index and compare it with the element at the next index i.e., 1st index [ if(b<a) where b is the element at the 1st index and a is the element at the 0th index when i = 1]. So we have 8<2, which is a wrong expression. Since, it is a wrong expression, we will not be modifying the array. Next, we compare the 0th index element with the second index element (15<2) and it is again a wrong expression, so the array is still safe and we will not make any changes to it. The next number to be compared is the element at the 3rd index. So we compare the element at 1st index with that at the 3rd index (1<2), and this expression is satisifed, so we will swap the places of 1(element at the 3rd index) and 2(element at 1st index) . Then, the element at the 0th index(which is 1) is compared to the next element(i.e., element at 4th index) which will be 6<1 and since this is not correct, no changes are made.

This process is repeated using a for loop(to be precise, the outer for loop) and it is iterated for ‘n’ times. After all the iterations, the array is successfully sorted.

 

 

Bubble Sorting

 

The following program illustrates Bubble Sort technique.

 

class BubbleSort //Line 1 – Declaring class BubbleSort

//Line 2 – class starts here

    static void test() //Line 3 – Declaring method ‘test’ as void

    { //Line 4 – method starts here

        int arr[] = {2,1,47,15,36,48,12}; //Line 5 – Declaring Integer type array ‘arr’

        int n = 7; //Line 6 – Declaring ‘n’ as int type and storing the number of elements in the array in it

        for(int i = 1;i<=(n-1);i++) //Line 7 – Outer for loop which runs from i=1 until i<=(n-1)

        { //Line 8 – outer for loop starts here

            for(int j = 0;j<(n-1);j++) //Line 9 – Inner for loop which iterates until the value of ‘j’ is between 0 and (n-1)

            { //Line 10 – inner for loop starts here

                int k = j+1; //Line 11 – Declaring int type variable ‘k’ and initializing it with j+1

                int a = arr[j]; //Line 12 – Declaring int type variable ‘a’ and storing the element at ‘j’ th index in it

                int b = arr[k]; //Line 13 – Declaring int type variable ‘b’ and storing the element at ‘k’ th index in it

                if(b<a) //Line 14 – Checking if b<a

                { //Line 15 – if block starts here

                    arr[j] = b; //Line 16 – Modifying the array, by changing the value at ‘j’ th index with the value of ‘b’

                    arr[k] = a; //Line 17 – Modifying the array, by changing the value at ‘k’ th index with the value of ‘b’

                } //Line 16 – if block ends here

            }  //Line 17 – inner for loop ends here

        } //Line 18 – outer for loop ends here

        for(int d = 0;d<n;d++) //Line 19 – for loop to display the resultant array

        System.out.print(arr[d]+” “); //Line 20 printing the ‘d’ th value of the resultant array

    } //Line 21 – method test ends here

//Line 22 – class ends here

 

Explanation of the Above Program

Once again, we have taken an Integer type array and initialized it with some sample values of Integer type. We are storing the number of elements of the array in a variable which we declared as Integer type.
The sample values that we have taken in the array are 2,1,47,15,36,48,12 . We will sort these in ascending order, but this time using Bubble sort techinque. 


Here are the elements of the array with their index numbers

Index Numbers :        0   ,   1    ,    2   ,    3    ,   4     ,    5    ,    6

 

Elements :                  2   ,   1   ,   47   ,   15   ,  36   ,   48   ,   12

Here is the algorithm of the Bubble sort. We first take the element at the 0 th index and compare it with the next element (element in the next index). For example, when i = 1 and j = 0 we compare (1<2) , since this is true, we swap the positions of these two elements. Now 1 is in the 0th index and 2 is in the 1st index. I am not going write the modified array , because I want you to imagine the modified array in your brain(No, I’m lying, the real reason is that I’m lazy to write the modified array). Anyways, now let’s continue the process. We now take the element at the 1st index and compare it with the element at the 2nd index (i.e., 47<2) and it is not satisfied, so we make no changes with the array. Next, take the element at 2nd index and compare it with that of 3rd index (i.e., 15<47) and the condition is satisfied, so we switch the postions of 15 and 47. Now, once again imagine the modified array in your brain. Then compare the 3rd index element with 4th index, and then compare the 4th index element with 5th index element, and finally compare the 5th index element with the 6th index and make changes to the array if the expression is satisfied. Alright, now we have successfully compared all the elements of the array and we modified the array accordingly. Let me right the final Array now. 

Index Numbers :        0   ,   1    ,    2   ,    3    ,   4     ,    5    ,    6

Elements :                  1   ,   2   ,   15   ,   36   ,  47   ,   12   ,   48

Oops, the array doesn’t seem to be sorted. Where have we done the mistake? 

The thing is, we still didn’t finish doing the Bubble sort thing. We have to repeat this process using a for loop until the array gets sorted completely. But wait, how many times should we iterate this process? Well, take your book and pen (you don’t need a book and pen if you have a capable brain like me, just kidding I even doubt if I have a brain)  and work on this thing, and you will find out that whatever the size of the array may be, this process should be repeated for (n-1) times in-order for the Array to get sorted (Note : n is the number of elements present in the Array) . So we will repeat this process for (n-1) times, and this time we won’t fail. We will get all the elements sorted in the ascending order.

So that’s all about Sorting Arrays in Java. if you have any doubts or suggestions for us, please feel free to comment below. We will respond immediately!

 

Teja Swaroop

Teja Swaroop

Founder of Tech Raj

Contact Email : teja.techraj156@gmail.com
Share This

Share This

Share this post with your friends!

Subscribe To Our Newsletter and Never Miss an Update!

Subscribe To Our Newsletter and Never Miss an Update!

Leave us your Email ID and we will notify you whenever we release new Videos, Articles or Apps.

You have Successfully Subscribed!