Insertion Sort

Problem

Read an array and print it sorted in ascending order. Use insertion sort.

Constraints

  • 1 <= n <= 2000

Examples

Input

6
5 2 9 1 5 6

Output

1 2 5 5 6 9

Solutions

Better approachTime O(n^2)Space O(1)

This is how many people sort playing cards in the hand. It is very fast on nearly sorted data (O(n)).

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Sort an array in ascending order.
 * Input   : n, then n integers.
 * Output  : The sorted array.
 * Approach: Insert into the sorted part.
 * Time    : O(n^2)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;
import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static int[] solve(int[] a) {
        // Step 1: The part to the left of index i is already sorted. The first element alone is sorted.
        for (int i = 1; i < a.length; i++) {
            // Step 2: Take the next value. It must be inserted into the sorted part.
            int value = a[i];
            int j = i - 1;

            // Step 3: Shift bigger values one place to the right.
            while (j >= 0 && a[j] > value) {
                a[j + 1] = a[j];
                j--;
            }

            // Step 4: Put the value in the free place.
            a[j + 1] = value;
        }
        return a;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        System.out.println(Arrays.stream(solve(a)).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
    }
}
Hints (1)
  1. What happens to the bigger values while you insert?