This is my solution for HackerRank's first "Algorithm Challenge, Insertion Sort Part 1". The challenge is to sort the array from least to greatest, the input being an array in sorted order, except for the last entity, i.e. {2, 3, 4, 5, 6, 7, 8, 9, 1}
It works fine, but it's definitely not an optimal solution. Could anybody provide any insights on how I should look at it so as to optimize it? This is for learning purposes, so I can apply the same concepts to future code.
static void insertionSort(int[] ar) {
int i, j;
int inserted = 0;
i = ar[ar.length-1];
for (j = ar.length-2; j > -1; j--){
if (ar[j] > i){
ar[j+1] = ar[j];
printArray(ar);
} else if (ar[j] <= i){
ar[j+1] = i;
inserted = 1;
break;
}
}
if(inserted == 0){
ar[0] = i;
}
printArray(ar);
}
This is the rest of the code, but it's preset and is already available:
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);
}
if (ar[j] > i)
is wrong then you don't need to checkelse if (ar[j] <= i)
because it is going to be true. \$\endgroup\$