Search This Blog

Sunday, September 15, 2013

Hacker Rank Problem - Sorting - Insertion Sort - Part 1

Insertion Sort - Part 1
The following is the solution to the Hacker Rank Problem "Insertion Sort - Part 1" using Java. Solutions to other Hacker Rank Problems are available in the following page HackerRank.

Score: 1/1
/**
 * @author Arun.G
 *
 */
/* Head ends here */
import java.util.*;
public class Solution {
      
          static void insertionSort(int[] ar) {
           
              int newvalue = ar[ar.length-1];
           for(int i=ar.length-1;i>0;i--)
           {
               if(newvalue<ar[i-1])
               {
                ar[i]=ar[i-1];
                printArray(ar);  
               }
               else
               {
                   ar[i]=newvalue;
                    printArray(ar);
                   return;
               }   
           }
           ar[0] = newvalue;
           printArray(ar);
             
       }  

/* Tail starts here */

 static void printArray(int[] ar) {
         for(int n: ar){
            System.out.print(n+" ");
         }
           System.out.println("");
      }
      
      public static void main(String[] args) {
           Scanner in = new Scanner(System.in);
           int n = in.nextInt();
           int[] ar = new int[n];
           for(int i=0;i<n;i++){
              ar[i]=in.nextInt();
           }
           insertionSort(ar);
       }   
   }

No comments:

Post a Comment

Labels