fork(1) download
  1. /**
  2.  * Insertion Sort Implementation
  3.  * @author Prateek
  4.  */
  5. class InsertionSort {
  6. /**
  7. * Insertion Sort Subroutine
  8. */
  9. public int[] insertionSort(int[] arr)
  10. {
  11. int size = arr.length;
  12. for(int i=1;i<size;i++){
  13. int j=i;
  14. int num=arr[i];
  15. while(j>0 && arr[j-1] > num){
  16. arr[j]=arr[j-1];
  17. j--;
  18. }
  19. arr[j]=num;
  20. }
  21. return arr;
  22. }
  23.  
  24. public static void main(String[] args) {
  25. int arr[]={1,5,4,7,3,12,5,9,2,8};
  26.  
  27. InsertionSort obj= new InsertionSort();
  28. System.out.println("Before Sorting:");
  29. obj.display(arr);
  30.  
  31. int[] sorted=obj.insertionSort(arr);
  32. System.out.println("After Sorting:");
  33. obj.display(sorted);
  34. }
  35.  
  36. /**
  37. * Display Array
  38. */
  39. public void display(int[] arr)
  40. {
  41. for(int i=0;i<arr.length;i++)
  42. System.out.print(arr[i]+"\t");
  43. System.out.println();
  44. }
  45. }
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
Before Sorting:
1	5	4	7	3	12	5	9	2	8	
After Sorting:
1	2	3	4	5	5	7	8	9	12