Insertion Sort(Java Implementation)

public class Sort {

public static void main(String[] strr) {

int arr[] = {9,8,7,6,5,4,3,2,1};

System.out.println(" Before sorting");

for(int j=0;j<=arr.length-1;j++)

{

System.out.print(" "+arr[j]);

}

new Sort().insertionSort(arr);

System.out.println("\nAfter Sorting");

for(int j=0;j<=arr.length-1;j++)

{

System.out.print(" "+arr[j]);

}

}

public void insertionSort(int arr[]) {

int temp;

for(int i=1;i<=arr.length-1;i++) {

temp=arr[i];

int j;

for (j=i-1; j>=0; j-- ) {

if(arr[j]>temp)

arr[j+1]=arr[j];

}

arr[j+1]=temp;

}

}

}

Output:

Before sorting
9 8 7 6 5 4 3 2 1
After Sorting
1 2 3 4 5 6 7 8 9

Leave a Reply