Insertion sort java arraylist

Let’s learn insertion sort java arraylist.

Insertion sort java arraylist

Here’s the insertion sort arraylist.

import java.util.ArrayList;
public class SortArrayList
{
   private static ArrayList<Integer> arrInput = new ArrayList<Integer>();
   public static ArrayList<Integer> getInputArray()
   {
      return arrInput;
   }
   // print array
   public SortArrayList(ArrayList<Integer> inputArray)
   {
      SortArrayList.arrInput = inputArray;
   }
   public void sortArray()
   {
      for(int a = 1; a < arrInput.size(); a++)
      {
         int key = arrInput.get(a);
         for(int b = a - 1; b >= 0; b--)
         {
            if(key < arrInput.get(b))
            {
               arrInput.set(b + 1, arrInput.get(b));
               if(b == 0)
               {
                  arrInput.set(0, key);
               }
            }
            else
            {
               arrInput.set(b + 1, key);
               break;
            }
         }
      }
   }
}
import java.util.ArrayList;
public class InsertionSortArrayList
{
   public static void main(String[] args)
   {
      ArrayList<Integer> al = new ArrayList<Integer>();
      al.add(9);
      al.add(5);
      al.add(2);
      al.add(8);
      al.add(3);
      al.add(1);
      al.add(7);
      SortArrayList sal = new SortArrayList(al);
      System.out.println("Given array: ");
      for(int a : SortArrayList.getInputArray())
      {
         System.out.print(a + " ");
      }
      sal.sortArray();
      System.out.println("\nSorted array: ");
      for(int a : SortArrayList.getInputArray())
      {
         System.out.print(a + " ");
      }
   }
}


Output:

Given array:
9 5 2 8 3 1 7
Sorted array:
1 2 3 5 7 8 9