Core Java program to sort the elements of an array.

Hey there!

Welcome to ClearUrDoubt.com.

In this post, we will look at a Core Java program to sort the elements of an array.

We will use the Insertion Sort technique to sort the array elements. Insertion Sort is good for small datasets.

Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there. It repeats until no input elements remain.

Let’s look at an example flow for {5, 12, 92, 76, 1, 58, 10, 2, 5}:

Outer Loop iteration Inner Loop iteration Array current Action to be done
1 0 5 12 92 76 1 58 10 2 5 12 no need to move
2 0 5 12 92 76 1 58 10 2 5 92 no need to move
3 1 5 12 92 76 1 58 10 2 5 76 Move 92 to next position
5 12 76 92 1 58 10 2 5 76 Insert 72 in previous position
4 1 5 12 76 92 1 58 10 2 5 1 Move 92 to next position
2 5 12 76 92 58 10 2 5 1 Move 76 to next position
3 5 12 76 92 58 10 2 5 1 Move 12 to next position
4 5 12 76 92 58 10 2 5 1 Move 5 to next position
1 5 12 76 92 58 10 2 5 1 Insert 1 in previous position
5 1 1 5 12 76 92 58 10 2 5 58 Move 92 to next position
2 1 5 12 76 92 10 2 5 58 Move 76 to next position
3 1 5 12 58 76 92 10 2 5 58 Insert 58 in previous position
6 1 1 5 12 58 76 92 10 2 5 10 Move 92 to next position
2 1 5 12 58 76 92 2 5 10 Move 76 to next position
3 1 5 12 58 76 92 2 5 10 Move 58 to next position
4 1 5 12 58 76 92 2 5 10 Move 12 to next position
1 5 10 12 58 76 92 2 5 10 Insert 10 in previous position
7 1 1 5 10 12 58 76 92 2 5 2 Move 92 to next position
2 1 5 10 12 58 76 92 5 2 Move 76 to next position
3 1 5 10 12 58 76 92 5 2 Move 58 to next position
4 1 5 10 12 58 76 92 5 2 Move 12 to next position
5 1 5 10 12 58 76 92 5 2 Move 10 to next position
6 1 5 10 12 58 76 92 5 2 Move 5 to next position
1 2 5 10 12 58 76 92 5 2 Insert 2 in previous position
8 1 1 2 5 10 12 58 76 92 5 5 Move 92 to next position
2 1 2 5 10 12 58 76 92 5 Move 76 to next position
3 1 2 5 10 12 58 76 92 5 Move 58 to next position
4 1 2 5 10 12 58 76 92 5 Move 12 to next position
5 1 2 5 10 12 58 76 92 5 Move 10 to next position
1 2 5 5 10 12 58 76 92 5 Insert 5 to next position

We can observe that after each outer loop iteration, the array is sorted till the outer loop index. The inner loop is used for moving the elements to next positions.

 

Here is the program:

Output:

Happy Learning :).

Please leave a reply in case of any queries.

Leave a Reply

Your email address will not be published. Required fields are marked *