Correctness and the Loop Invariant
The following is the solution to Hacker Rank problem Running Time of Algorithms using Java. For solutions to other Hacker Rank Problem visit my page HackerRank, alternatively try searching for the problem in my blog.
Score: 1/1
/**
*
*/
import java.util.Scanner;
/**
* @author Arun.G
*
*/
public class Solution{
/**
* @param args
*/
public static int insertionSort(int[] A){
int noOfShifts=0;
for(int i = 1; i < A.length; i++){
int value = A[i];
int j = i - 1;
while(j >= 0 && A[j] > value){
A[j + 1] = A[j];
j = j - 1;
noOfShifts++; //count the number of shifts
}
A[j + 1] = value;
}
return noOfShifts;
}
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();
}
System.out.println(insertionSort(ar));
in.close(); //close the
scanner
}
}
|
No comments:
Post a Comment