How To Implement Insertion Sort

This recipe shows how to implement insertion sort.

Problem:

Given an unsorted array of strings, sort the strings in ascending order.

Solution:

public class InsertionSort {

    public static void sort(String[] data) {
        for (int i = 1; i < data.length; i++) {
            for (int j = i; j > 0; j--) {
                if (data[j - 1].compareTo(data[j]) > 0) {
                    swap(data, j - 1, j);
                } else {
                    break;
                }
            }
        }
    }

    private static void swap(String[] data, int i, int j) {
        final String temp = data[i];
        data[i] = data[j];
        data[j] = temp;
    }

    public static void main(String[] args) throws IOException {
        try (final BufferedReader bf = new BufferedReader(new InputStreamReader(System.in))) {
            // read data from standard input
            String line;
            final List<String> data = new ArrayList<>();
            while (true) {
                line = bf.readLine();
                if ((line == null) || line.isEmpty()) {
                    break;
                }
                data.add(line);
            }

            // terminate if no data was read
            if (data.isEmpty()) {
                return;
            }

            // convert list to array
            final String[] strings = data.toArray(new String[0]);

            // sort
            sort(strings);

            // output
            for (String sortedString : strings) {
                System.out.println(sortedString);
            }
        }
    }
}

Link To: Java Source Code

Solution Notes:

Time Complexity: O(n2)

Space Complexity: O(1)

Sources: