Monday, June 6, 2016

Insertion Sort in Java

Insertion sort is a simple sorting algorithm that orders a list one element at a time. It goes through the list and picks out each element and then goes back through the list until it finds its place. Here is working code in Java:

public class Sort {

    public static void main(String[] args) {
        int[] x = {10,11,7,6,5,4,3,2,14,3,8,9,2,5,1};
       
        int[] selectionSortArray = selectionSort(x, x.length);
        for(int i : selectionSortArray)
            System.out.print(i + ",");
    }
   
    public static int[] selectionSort(int[] list, int length)
    {
        int[] listTemp = list;
        int size = length;
        int j = 0;
        for(int i = 1; i < length; i++)
        {
            j = i;
            while(j > 0 && listTemp[j-1] > listTemp[j])
            {
                int temp = listTemp[j-1];
                int temp2 = listTemp[j];
                listTemp[j-1] = temp2;
                listTemp[j] = temp;
                j--;
            }
        }
        return listTemp;
    }

}

No comments:

Post a Comment