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.
  • Hackerrank Home
  • Prepare
    NEW
  • Certify
  • Compete
  • Career Fair
  • Hiring developers?
  1. Prepare
  2. Algorithms
  3. Sorting
  4. Running Time of Algorithms
  5. Discussions

Running Time of Algorithms

Problem
Submissions
Leaderboard
Discussions

    You are viewing a single comment's thread. Return to all comments →

  • RodneyShag
    5 years ago+ 0 comments

    Java solution - passes 100% of test cases

    From my HackerRank solutions.

    import java.util.Scanner;
    
    public class Solution {
    
        public static void insertionSortShiftCounter(int[] array) {
            int shifts = 0;
            for (int i = 1; i < array.length; i++) {
                int j = i;
                int value = array[i];
                while (j >= 1 && array[j-1] > value) {
                    array[j] = array[j-1];
                    j--;
                    shifts++;
                }
                array[j] = value;
            }
            System.out.println(shifts);
        }
        
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            int s = scan.nextInt();
            int[] array = new int[s];
            for (int i = 0; i < s; i++) {
                array[i] = scan.nextInt(); 
            }
            insertionSortShiftCounter(array);
        }
    }
    

    Let me know if you have any questions.

    6|
    Permalink
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature