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.
importjava.io.*;importjava.util.*;importjava.text.*;importjava.math.*;importjava.util.regex.*;publicclassMyClass{publicstaticvoidmain(Stringargs[]){// Initialize Scanner to take input from the userScannerin=newScanner(System.in);// Read the size of the arrayintn=in.nextInt();int[]arr=newint[n];// Input all elements of the arrayfor(inti=0;i<n;i++){arr[i]=in.nextInt();}// Store the last element of the array (key to be inserted)intcurr=arr[n-1];inti=0;// Loop to shift elements to the right if they are greater than 'curr'for(i=n-2;i>=0;i--){// If the current element is smaller than 'curr', place 'curr' hereif(arr[i]<curr){arr[i+1]=curr;break;// Exit the loop after insertion}else{// Shift the element to the rightarr[i+1]=arr[i];}// Print the array after each shiftfor(intj=0;j<n;j++){System.out.print(arr[j]+" ");}System.out.println();}// If no valid position was found in the loop, place 'curr' at the beginningif(i==-1){arr[0]=curr;}// Print the final state of the arrayfor(intj=0;j<n;j++){System.out.print(arr[j]+" ");}}}
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 1
You are viewing a single comment's thread. Return to all comments →
Java easy code: