Selection Sort

Problem

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

Constraints

  • 1 <= n <= 2000

Examples

Input

6
5 2 9 1 5 6

Output

1 2 5 5 6 9

Solutions

Brute forceTime O(n^2)Space O(1)

We repeatedly select the smallest remaining value and put it at the front of the unsorted part. It makes at most n - 1 swaps.

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: Select the minimum.
 * 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) {
        int n = a.length;

        // Step 1: For each position, find the smallest value in the rest of the array.
        for (int position = 0; position < n - 1; position++) {
            int smallest = position;

            // Step 2: Scan the unsorted part.
            for (int i = position + 1; i < n; i++) {
                if (a[i] < a[smallest]) {
                    smallest = i;
                }
            }

            // Step 3: Put the smallest value at the current position.
            int temporary = a[position];
            a[position] = a[smallest];
            a[smallest] = temporary;
        }
        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. Which part of the array is sorted after step k?