/**
* Insertion Sort Implementation
* @author Prateek
*/
class InsertionSort {
/**
* Insertion Sort Subroutine
*/
public int[] insertionSort(int[] arr)
{
int size = arr.length;
for(int i=1;i<size;i++){
int j=i;
int num=arr[i];
while(j>0 && arr[j-1] > num){
arr[j]=arr[j-1];
j--;
}
arr[j]=num;
}
return arr;
}
public static void main
(String[] args
) { int arr[]={1,5,4,7,3,12,5,9,2,8};
InsertionSort obj= new InsertionSort();
System.
out.
println("Before Sorting:"); obj.display(arr);
int[] sorted=obj.insertionSort(arr);
System.
out.
println("After Sorting:"); obj.display(sorted);
}
/**
* Display Array
*/
public void display(int[] arr)
{
for(int i=0;i<arr.length;i++)
System.
out.
print(arr
[i
]+"\t"); }
}
LyoqCiAqIEluc2VydGlvbiBTb3J0IEltcGxlbWVudGF0aW9uCiAqIEBhdXRob3IgUHJhdGVlawogKi8KY2xhc3MgSW5zZXJ0aW9uU29ydCB7CgkvKioKCSAqIEluc2VydGlvbiBTb3J0IFN1YnJvdXRpbmUKCSAqLwoJcHVibGljIGludFtdIGluc2VydGlvblNvcnQoaW50W10gYXJyKQoJewoJCWludCBzaXplID0gYXJyLmxlbmd0aDsKCQlmb3IoaW50IGk9MTtpPHNpemU7aSsrKXsKCQkJaW50IGo9aTsKCQkJaW50IG51bT1hcnJbaV07CgkJCXdoaWxlKGo+MCAmJiBhcnJbai0xXSA+IG51bSl7CgkJCQlhcnJbal09YXJyW2otMV07CgkJCQlqLS07CgkJCX0KCQkJYXJyW2pdPW51bTsKCQl9CgkJcmV0dXJuIGFycjsKCX0KCglwdWJsaWMgc3RhdGljIHZvaWQgbWFpbihTdHJpbmdbXSBhcmdzKSB7CgkJaW50IGFycltdPXsxLDUsNCw3LDMsMTIsNSw5LDIsOH07CgkJCgkJSW5zZXJ0aW9uU29ydCBvYmo9IG5ldyBJbnNlcnRpb25Tb3J0KCk7CgkJU3lzdGVtLm91dC5wcmludGxuKCJCZWZvcmUgU29ydGluZzoiKTsKCQlvYmouZGlzcGxheShh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