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.
Commented for anyone struggling with the model rather than the coding.
// amended Solution class to pass int[] arr.// also require return type long for 6 of the test cases.publicstaticlonginsertionSort(int[]arr){// min size of passed arr[] to sort is 2 elements.if(arr.length<=1){return0;}intmid=arr.length/2;// split array into 2. copyOfRange excludes end index.int[]left=Arrays.copyOfRange(arr,0,mid);int[]right=Arrays.copyOfRange(arr,mid,arr.length);// recursive call to split arr[] until we're down to pairs ->// once in pairs, start sorting arr[] whilst counting the insert shifts // recursively passed back up for parent to continue count// on its own arr[] (now sorted - left[] right[].longcount=insertionSort(left)+insertionSort(right);// i keeps track of left[], j of right[], k tracks arr[]inti=0;intj=0;intk=0;// scroll through left[] and compare <= with right values// count shifts from right->left AND make changes to arr[]while(i<left.length&&j<right.length){if(left[i]<=right[j]){arr[k++]=left[i++];}else{arr[k++]=right[j++];count+=left.length-i;}}// once swept through all of either left or right, // now assign remaining tail to arr[]while(i<left.length){arr[k++]=left[i++];}while(j<right.length){arr[k++]=right[j++];}// now return count for this child sweep/sort -> // Original arr[] updated for parent sweep/count/sort// Eventually returns to first split for the final countreturncount;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Insertion Sort Advanced Analysis
You are viewing a single comment's thread. Return to all comments →
Commented for anyone struggling with the model rather than the coding.