Insertion-sort Program in Java

Amansingh Javatpoint
1 min readApr 18, 2021

--

We can create a java program to sort array elements using insertion sort. Insertion is good for small elements only because it requires more time for sorting large number of elements.

Let’s see a simple java program to sort an array using insertion sort algorithm.

  1. public class InsertionSortExample {
  2. public static void insertionSort(int array[]) {
  3. int n = array.length;
  4. for (int j = 1; j < n; j++) {
  5. int key = array[j];
  6. int i = j-1;
  7. while ( (i > -1) && ( array [i] > key ) ) {
  8. array [i+1] = array [i];
  9. i — ;
  10. }
  11. array[i+1] = key;
  12. }
  13. }
  14. public static void main(String a[]){
  15. int[] arr1 = {9,14,3,2,43,11,58,22};
  16. System.out.println(“Before Insertion Sort”);
  17. for(int i:arr1){
  18. System.out.print(i+” “);
  19. }
  20. System.out.println();
  21. insertionSort(arr1);//sorting array using insertion sort
  22. System.out.println(“After Insertion Sort”);
  23. for(int i:arr1){
  24. System.out.print(i+” “);
  25. }
  26. }
  27. }

ww.tutorialandexample.com/insertion-sort-in-java/

--

--

No responses yet