I have started learning Java recently and was looking into the challenges on sorting on Hackerrank.I solved the following problemHackerrank on Insertion Sort.
The challenge was :
In Insertion Sort Part 1, you sorted one element into an array. Using the same approach repeatedly, can you sort an entire unsorted array?
Guideline: You already can place an element into a sorted array. How can you use that code to build up a sorted array, one element at a time? Note that in the first step, when you consider an element with just the first element - that is already "sorted" since there's nothing to its left that is smaller.
In this challenge, don't print every time you move an element. Instead, print the array after each iteration of the insertion-sort, i.e., whenever the next element is placed at its correct position.
Since the array composed of just the first element is already "sorted", begin printing from the second element and on.
Input Format There will be two lines of input:
- the size of the array
- a list of numbers that makes up the array
Output Format : On each line, output the entire array at every iteration.
Sample Input:
6 1 4 3 5 6 2
Sample Output:
1 4 3 5 6 2 1 3 4 5 6 2 1 3 4 5 6 2 1 3 4 5 6 2 1 2 3 4 5 6
I am trying to get better at writing good code for my solutions..Please give me your suggestions .
import java.util.Scanner; public class InsertionSortPart2 { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); int size = keyboard.nextInt(); int[] array = new int[size]; for (int i = 0; i < array.length; i++) { array[i] = keyboard.nextInt(); } array = insertionsort(array); } private static int[] insertionsort(int[] a) { for (int i = 1; i < a.length; i++) { // set key to value at index i int key = a[i]; // set j as i-1 to look for previous element int j = i - 1; while (j >= 0 && a[j] > key) { a[j + 1] = a[j]; j--; } a[j + 1] = key; for (int f = 0; f < a.length; f++) { System.out.print(a[f] + " "); } System.out.println(); } return a; } }