Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Insertion Sort in Java: Explained with Examples

Updated on 05 June, 2023

5.65K+ views
7 min read

Basics of Sorting Algorithms in Java

Sorting refers to the arrangement of elements in a specific order, often used in data structures such as arrays. The criteria in which the elements are sequenced is diverse. The most common ones are the sorting of numbers in ascending and descending order, lexicographical sorting of strings etc. Some of the most common and effective sorting algorithms used in Java and other object-oriented programming languages are:

  • Bubble sort
  • Selection sort
  • Insertion sort
  • Merge sort
  • Quicksort
  • Heapsort

Insertion sort is an easy-to-understand sorting algorithm whose working is similar to the manner we play cards. The input array list is split into two parts: sorted and unsorted. The splitting is virtual. The items from the unsorted part of the list are shifted to the sorted portion one at a time in each iteration.

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

Implementation of Insertion Sort in Java

In insertion sort, the current element is compared with the immediate next element in each pass. The comparison is made to determine if the element is greater than the element it is compared to. If the item is greater than the one it is compared to, it is retained in the same position and the iteration continues. If the item is lesser than the one it is compared to, it is shifted to its appropriate position by shifting the larger items by one position backwards.

An example for Insertion Sort

Figure 1 Insertion Sort Example

In the insertion sorting algorithm, the first iteration starts with an assumption that the item at the 0th position is already sorted. For each iteration, the current item is checked against the items in the sorted region of the list. The items that are greater during the comparison are moved towards the right of the list. In this algorithm, the current item can be inserted when the smaller item is reached.

Figure 1 shows an example of an insertion sort with a list of items. In the first iteration, the element [54] is assumed to be sorted already. This acts as a reference for the comparison during the first iteration. The second element [26] is less than 54 and hence, 54 is moved to the right. 

Check out our free technology courses to get an edge over the competition.

Example Java Code for an Insertion Sort

Now that we have gained knowledge about the working of the insertion sort algorithm let’s visualize how a Java code is written to sort the elements with this algorithm. In the example code shown below, the values of arr can be changed as per your needs and how the program responds for different input arrays. 

The output of the above code is mentioned below.

Explanation of the implemented Java code:

  • As an initial step in the program, a method to accept the input array to be sorted is created. It is referred to as sort_arr in the above code.
  • Secondly, an outer for loop is created to iterate over each element of the input array, as reflected in line 5 of the above code.
  • The next step is the creation of a distinct iterator ‘j’ to evaluate for the sorting of the elements in ascending order of the input list. This is shown in the 7th line of the code.
  • In the next step, an inner while loop is created.
    • The while loop is expected to meet two specified conditions as in line 9 of the code. The two conditions are that the j’s value must be more than 0 and the j-1 index value must be more than the j’s index value. 
    • If both the conditions evaluate to true, lines 11 to 14 are executed and the j’s index value is assigned as the key’s value. 
    • The values at j-1 and j are exchanged. 
    • j’s value decrements by 1 and the loop repeats till any of the two conditions is evaluated to be false. 
  • The execution continues for each traverse of the outer for loop till the condition for that also breaks. 

Check out upGrad’s Advanced Certification in DevOps 

Advantages of Insertion sort in Java

  • Insertion sort in Java is a purely simple sorting algorithm.
  • There is no change in the comparative order of constituents of the list.
  • This sorting algorithm is able to sort the list as and when the list is received.
  • This sorting algorithm works effectively for small datasets.
  • The algorithm demands a constant quantity of extra space or memory. 

Insertion Sort In Java

Insertion sort is an efficient sorting algorithm that allows for in-place sorting of an array.

It follows one element at a time. In this sorting approach, the array is changed without any temporary structures. 

Characteristics Of Insertion Sort In Java

  • The implementation of this method is straightforward, making it one of the simplest.
  • In general, insert sort is effective for small data values.
  • The nature of insertion sort is adaptive.
  • Because linked lists contain pointers to both the next (singly linked list) and previous (doubly linked list) elements, insertion sort operations on them are simpler.
  • The insertion sort algorithm Java is frequently used in the following situations:
    • The array only has a few elements.
    • Only a few elements remain to sort.

Pseudocode

Below is the pseudocode for insertion sort in Java

INSERTION-SORT(array)

for i=2 to array.length

    key_element = array[i]

    j = i - 1 

    while j > 0 and array[j] > key_element

        array[j+1] = array[j]

        j = j - 1

    array[j + 1] = key_element

Let’s quickly review the algorithm mentioned above.

  • The current item in the array to be processed is indicated by the index i.
  • As an array with only one item is, by definition, considered to be sorted, we start with that item. 
  • A key is the thing that is at index i. 
  • The second step of the technique involves determining the right index once the key has been obtained.
  • The key shifts one position to the left if it exceeds the item’s value at index j. Up until the point where an element is smaller than the key, the operation continues.

Recursive approach

In the recursive approach of Insertion Sort Java Code, the following differences from the iterative approach are acknowledged:

  • It differs from the imperative case in that it calls an overloaded function with a second argument equal to the number of items to sort.
  • A little bit harder to handle is the recursive scenario. When trying to sort an array with only one item, the base case occurs. We take no action in this situation.
  • From the second item through the end of the array, each consecutive recursive call sorts a predetermined portion of the input array:

Complexity Explanation In All Cases

Worst Case – O(n2)

When the input sequence is in descending order, you wish to sort an array of numbers in ascending order. In this scenario, every element must be compared to every element to its left. This implies there are ‘n’ comparisons for each element after the first. There are hence ‘n(n-1)’ comparisons in total. Hence, the worst-case complexity for an input size of n is O(n2).

Best Case – O(n)

When the array is already sorted, the outer loop runs n times, and the inner loop is never called. Therefore, the best-case complexity for an input size of ‘n’ is O(n).

Average Case – O(n2)

The average case complexity for an input size of ‘n’, when the array components are arranged randomly, is O(n2).

Performance of Insertion Sort

  • Time complexity and space complexity of insertion sort are O (n2) and O (1), respectively.
  • (n2) assessments and switches are the worst-case performance of this sorting algorithm.
  • (n) comparisons and O (1) exchanges are the best-case performance of insertion sort.
  • The average case performance is also with O (n2) swaps and comparisons.

Demerits of Insertion Sort

  • The performance of insertion sort is not as good as other sorting algorithms.
  • This sorting algorithm is not suitable for huge lists because the number of steps required to sort the list is the square of the number of items in the list.

At upGrad, we understand the importance of practical, hands-on learning – especially when it comes to software development. As a result, our courses and training initiatives have practicality at their very core. One such initiative is Full Stack Development Bootcamp which will help you develop all the relevant skills required to excel in full-stack development. 

RELATED PROGRAMS