+ 1
Verify my insertion sort algorithm implementation [Java]
Hi, I have written my insertion sort in java. and it's different from other implementations on the internet. So, just verify that it is an insertion sort. public static void myInsertionSort(int[] a) { for (int i = 1; i < a.length; i++) { for (int j = i; j > 0; j--) { if (a[j-1] > a[j]) { int temp = a[j]; a[j] = a[j - 1]; a[j - 1] = temp; } } } System.out.println(Arrays.toString(a)); }
3 ответов
+ 4
I tested your code, and it works correctly and it follows the same pseudocode algorithm that is showcased on the wikipedia site
https://en.m.wikipedia.org/wiki/Insertion_sort
There are other, maybe more efficient variants, but this one looks good too.
I added some tests and moved the print inside the 'if' just to see how many swaps are performed. Seems fine to me.
https://code.sololearn.com/cL1k3Sxp620o/?ref=app
For the future, I suggest to save your working code in the playground, and link it to the question, that makes it much easier for people to help.
+ 2
Manjit Kumar yes, you are right, they are really similar! In fact, both bubble sort and insertion sort have O(n^2) worst case time complexity.
+ 1
@Tibor Santa
Thanks, For verifying it. I was thinking it looks similar to bubble sort.