Saturday, 4 June 2016

insertion sort implementation in java

in this  blogpost we will see what is insertion sort how it  can be implemented in java





what we have is an unsorted array , first we have to split the array in to two indices from 0 -> sorted array and from 0+1 -> length of the array an unsorted array  , so in the above array 4 is sorted and the rest of the array is unsorted so we are increasing the sorting array in the next iteration we are increasing the index to 1 , and then from end of the sorting array to the beginning of the sorted array we are comparing each elements we are comparing each elements if they are not sorted then we swap their positions , here the sorted array is from 0-1 and the elements are 4, 3 since it is not sorted we are swapping the two elements after swapping 


now 0-1 is sorted and we move the sorted index to 2 , and there are three elements then from index 2 to 0 we comparing if all the elements are sorted , first we compare the index 2 with 1 since it is  not sorted we swap the elements and move the cursor to one then we compare  index 1 with 0 since those elements were not sorted we swap them  after that the array will look like this 




then we increase the sorted index and repeat the process 


lets see how the code looks Like 





and it was run successfully against these following Test cases