Sorting an Array in Java: Simple Guide

sorting an array in java help

In computer programming, sorting is a very important aspect of the industry. It is used in numerous applications to make coding much easier. Imagine if there was no sorting, how messy would our lives be? Thus, in simpler terms, we can define sorting as the systematic ordering of a list of objects. Usually, sorting is broken down into 2 categories. The first is known as internal sorting. This is whereby we can fit a small number of objects into the main memory. You can easily figure it out by doing some basic java programming exercises.

Alternatively, we have external sorting; whereby the objects are so large and numerous in number; that we have to place some of them in an external storage during a sort. So today, we will be looking at how to sort an array in Java programming and what is two dimensional array in Java programming.

Sorting an Array in Java

Sorting in Java is a unique process that benefits programmers and developers as a whole. Today, we will discuss control flow of four different methods of sorting in Java.

1. Arrays of Primitives

Primitives in Java can be described as the simplest data types of the Java language. A number of good examples are byte, short, float, boolean e.t.c. Primitives are the building blocks of the language, and are used in multiple operations of Java. Whenever you want to sort an array of primitives, you can directly do so using the arrays.sort method as shown in a source code:

EXAMPLE

int[] a1 = {3,4,1,5,2,6};
Arrays.sort(a1);

2. Array of Objects

Object sorting in Java is unique in that it requires a given recommendation to be put in place before execution can take place. First and foremost, the objects should be mutually comparable. That means we need to know whether the objects are equal or if one is larger or smaller than the other. We can do so using the comparable interface. It contains the given method as shown below:

public int compareTo(Object obj);

The return value is dependent on the difference between the selected object and the parameter object. It can return a positive, negative or zero value. You will note a variation between the compare To() and equals() methods. For example, in the demonstration below, we will create a class of playing cards that are comparable to each other based on their values:

class Card implements Comparable<Card>
{
private String suit;
private int value;
public Card(String suit, int value)
{
this.suit = suit;
this.value = value;
}
public int getValue()
{
return value;
}
public String getSuit()
{
return suit;
}
public int compareTo(Card x)
{
return getValue() - x.getValue();
}
}

Now, let us say that the Card class executes along with it the comparable interface, then we can, therefore, sort a group of cards by initiating the Arrays.sort method.

Card[] hand = new Card[5];
Random rand = new Random();
for (int i = 0; i ‹ 5; i++)
hand[i] = new Card(rand.nextInt(5), rand.nextInt(12));
Arrays.sort(hand);

3. Collection of Comparable Objects

In a collection, you can sort mutually comparable objects using the following sort method:

ArrayList‹Integer> a2 = new ArrayList‹Integer> (5);
...
Collections.sort(a2);

4. Comparator

As is observed, the comparable interface does not offer a satisfying solution to the main problem of the above codes; which only work for objects that have a certain execution of the compare To method. Once it is implemented, there is limited flexibility. Furthermore, it is not always doable to decide on a practical method for compareTo. Therefore, this method can be based on a number of ideas. The commendable solution to this issue is to take the comparison function as if it is a parameter. This comparison function in Java could be implemented using the Comparator interface.

 

For example, let us consider something like a poker hand; in order to do a fast evaluation, you would first want to sort the cards present either by suit or by value. So to be able to support these two different criteria’s, we then need to create two classes. One of them is SortByValue while the other is SortBySuit; which will, in turn, implement the Comparator Interface.

class SuitSort implements Comparator
{
public int compare(Object x, Object y)
{
int a = ((Card) x).getSuit();
int b = ((Card) y).getSuit();
return a-b;
}
}

You can then execute a comparison function to that of a sorting routine as is demonstrated below:

Arrays.sort(hand, new SuitSort());

The new object shown above (SuitSort) is known as a functor, and this kind of programming is known as functional programming. The functor is simply a class that has no data present, but contains a single method. We can, therefore, design a number of comparison functions through the declaration of new classes; each suited for a different type of function.

learn how to sort an array in java programming

What Is 2 Dimensional Array in Java Programming?

A 2D array is one that has an array type with 2 pairs of square brackets as shown: int[][] or float[][]. The elements present in these type of arrays are arranged in columns and rows as shown below:

int[][] A;
A = new int[3][4];

This then creates a 2D array that has 3 rows and 4 columns. When it comes to sorting 2D arrays, there are 2 methods that can be applied.

Dive into the world of Java socket programing now and we will help you figure things out!

1. Converting the 2D into 1D Then Sorting It


The code below demonstrates how to convert 2D to 1D then sorting it.

/**
* The class Sort2D_Method1 inputs a two dimensional array and sorts it in ascending order
* @author : www.javaforschool.com
* @Program Type : BlueJ Program - Java
*/
import java.io.*;
class Sort2D_Method1
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the no. of  rows: "); //inputting number of rows
int m=Integer.parseInt(br.readLine());
System.out.print("Enter the no. of columns: "); //inputting number of columns
int n=Integer.parseInt(br.readLine());
int A[][]=new int[m][n]; //creating a 2D array
/* Inputting the 2D Array */
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
System.out.print("Enter the elements: ");
A[i][j]=Integer.parseInt(br.readLine());
}
}        
/* Printing the original 2D Array */
System.out.println("The original array:");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(A[i][j]+"\t");
}
System.out.println();
}
/* Saving the 2D Array into a 1D Array */
int B[]=new int[m*n]; //creating a 1D Array of size 'r*c'
int x = 0;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
B[x] = A[i][j];
x++;
}
}
/*Sorting the 1D Array in Ascending Order*/
int t=0;
for(int i=0; i<(m*n)-1; i++)
{
for(int j=i+1; j<(m*n); j++)
{
if(B[i]>B[j])
{
t=B[i];
B[i]=B[j];
B[j]=t;
}
}
}
/*Saving the sorted 1D Array back into the 2D Array */
x = 0;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
A[i][j] = B[x];
x++;
}
}
/* Printing the sorted 2D Array */
System.out.println("The Sorted Array:");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(A[i][j]+"\t");
}
System.out.println();
}
}
}

2. Sorting the 2D Array Directly


The code below shows the direct application of 2D array sorting.

/**
* The class Sort2D_Method2 inputs a two dimensional array and sorts it in ascending order
* @author : www.javaforschool.com
* @Program Type : BlueJ Program - Java
*/
import java.io.*;
class Sort2D_Method2
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the no. of  rows: "); //inputting number of rows
int m=Integer.parseInt(br.readLine());
System.out.print("Enter the no. of columns: "); //inputting number of columns
int n=Integer.parseInt(br.readLine());
int A[][]=new int[m][n]; //creating a 2D array
/* Inputting the 2D Array */
for(int i=0;i<m;i++)
{>
for(int j=0;j<n;j++)
{
System.out.print("Enter the elements: ");
A[i][j]=Integer.parseInt(br.readLine());
}
}        
/* Printing the original 2D Array */
System.out.println("The original array:");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(A[i][j]+"\t");
}
System.out.println();
}
/* Sorting the 2D Array */
int t=0;
for(int x=0;x<m;x++)
{
for(int y=0;y<n;y++)
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(A[i][j]>A[x][y])
{
t=A[x][y];
A[x][y]=A[i][j];
A[i][j]=t;
}
}
}
}
}
/* Printing the sorted 2D Array */
System.out.println("The Sorted Array:");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(A[i][j]+"\t");
}
System.out.println();
}
}>
}

Therefore, once you’ve mastered the art of array sort in Java in both applications of 1 dimensional and 2-dimensional arrays, then you’re good to go!

And if you’d like to find out more about sorting in Java programming, our services can definitely get you going in the direction. Learn more about us by getting in touch with some of our professional developers.