I am learning data structures, and have written an algorithm for insertion sort after learning from some sources. But I am confused which implementation is more correct or appropriate.
Code #1 This implementation takes an element and sorts itself with all the elements to its left, one by one, like bubble sort I think. I am just sorting and I think I can not say I am inserting an element to its correct location.
public static int[] insertionSortAsc(int[] elemArr){
int len = elemArr.length;
int temp;
for (int i=0; i<= (len-2); i++){
for (int j=(i+1); j>0; j--){
if (elemArr[j] < elemArr[j-1]){
//swap
temp = elemArr[j];
elemArr[j] = elemArr[j-1];
elemArr[j-1] = temp;
}
}
}
return elemArr;
}
Code #2 This implementation takes an element into a 'temp' variable, compares it with left elements in the array and sorts them by comparing with the 'temp' element. When sorting stops, which means that the left side is sorted corresponding the 'temp' element, then this is element is put into that last location.
public static int[] insertionSort(int[] elements) {
for (int i=1; i<elements.length; i++) {
int j, elem_i = elements[i];
for (j=i; j>0 && elements[j-1] > elem_i; j--) {
elements[j] = elements[j-1];
}
elements[j] = elem_i;
}
return elements;
}
I also have another idea though I have not written the code which I think matches my thought about the meaning of insertion sort.
- Create an array, sortArr, of same size as that of input array.
- Find the minimum element, and put that to sortArr[0]. If more elements with same value, put them into successive locations and maintain the count, means the index to which value is filled into sortArr. Put this minimum element to some tempMin variable.
- Now check for another element in the original array which is just greater than tempMin, if found, replace the value of tempMin with this value, and then copy this to sortArr according to the filling count variable, increase the count thereby.
- Repeat steps 2 and 3, until filling count variable reaches array length.
- Exit.
I might be wrong but that is my thought. Please suggest algorithm modifications or my thinking if I am wrong.