Verify my insertion sort algorithm implementation [Java] | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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)); }

28th Nov 2020, 2:44 AM
Manjit Kumar
Manjit Kumar - avatar
3 Answers
+ 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.
28th Nov 2020, 3:33 AM
Tibor Santa
Tibor Santa - avatar
+ 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.
28th Nov 2020, 6:03 AM
Tibor Santa
Tibor Santa - avatar
+ 1
@Tibor Santa Thanks, For verifying it. I was thinking it looks similar to bubble sort.
28th Nov 2020, 5:48 AM
Manjit Kumar
Manjit Kumar - avatar