We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
My Java solution with o(n^2) time complexity and o(1) space complexity:
publicstaticvoidinsertionSort2(intn,List<Integer>arr){if(n==1)System.out.println(arr.get(0));//len of 1 is already sorted//separate arr into sorted and unsorted portionsfor(inti=1;i<arr.size();i++){intj=i-1;intcurrVal=arr.get(i);intprevVal=arr.get(j);//compare prev element with curr elementif(currVal<prevVal){while(currVal<prevVal){arr.set(j+1,prevVal);arr.set(j,currVal);j--;if(j>=0)prevVal=arr.get(j);elsebreak;}}//print the arrarr.forEach(l->System.out.print(l+" "));System.out.println();}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Insertion Sort - Part 2
You are viewing a single comment's thread. Return to all comments →
My Java solution with o(n^2) time complexity and o(1) space complexity: