Bubble Sort

Problem

Read an array and print it sorted in ascending order. Use bubble 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)

Big values move to the end like bubbles move up. Each pass puts one more value at its final place. The early stop makes the best case 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: Swap neighbours.
 * 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: Repeat the pass n - 1 times. After pass k, the k largest values are at the end.
        for (int pass = 0; pass < n - 1; pass++) {
            boolean swapped = false;

            // Step 2: Compare neighbours. The end part is already sorted, so we skip it.
            for (int i = 0; i < n - 1 - pass; i++) {
                // Step 3: If the left value is bigger, swap the two values.
                if (a[i] > a[i + 1]) {
                    int temporary = a[i];
                    a[i] = a[i + 1];
                    a[i + 1] = temporary;
                    swapped = true;
                }
            }

            // Step 4: No swap in a full pass means the array is sorted. We can stop early.
            if (!swapped) {
                break;
            }
        }
        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 value is at the end after the first pass?