Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java Exercises: Insertion sort Algorithm

Java Sorting Algorithm: Exercise-7 with Solution

Write a Java program to sort an array of given integers using Insertion sort Algorithm.

Note:
Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than other algorithms such as quicksort, heapsort, or merge sort.


Pictorial presentation - Insertion search algorithm :

Java programming Insertion sort algorithm

Sample Solution:

Java Code:

import java.util.Arrays;

public class InsertionSort {
  void InsertionSort(int[] nums){
  for(int i = 1; i < nums.length; i++){
    int value = nums[i];
    int j = i - 1;
    while(j >= 0 && nums[j] > value){
      nums[j + 1] = nums[j];
      j = j - 1;
    }
    nums[j + 1] = value;
  }
}
    
	// Method to test above
    public static void main(String args[])
    {
        InsertionSort ob = new InsertionSort();
        int nums[] = {7, -5, 3, 2, 1, 0, 45};
        System.out.println("Original Array:");
        System.out.println(Arrays.toString(nums));
        ob.InsertionSort(nums);
        System.out.println("Sorted Array");
        System.out.println(Arrays.toString(nums));
    }
}

Sample Output:

[7, -5, 3, 2, 1, 0, 45]
Sorted Array
[-5, 0, 1, 2, 3, 7, 45]

Flowchart:

Flowchart: Sort an array of given integers using the Insertion sort Algorithm..

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to sort an array of given integers using Selection Sort Algorithm.
Next: Write a Java program to sort an array of positive integers using the Bead Sort Algorithm.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe