/// Returns a sorted copy of items, using bubble sort with early exit.
int[] bubbleSort(int[] items) {
    int[] result = Arrays.copyOf(items, items.length);
    int n = result.length;

    for (int i = 0; i < n; i++) {
        boolean swapped = false;
        for (int j = 0; j < n - i - 1; j++) {
            if (result[j] > result[j + 1]) {
                int temp = result[j];
                result[j] = result[j + 1];
                result[j + 1] = temp;
                swapped = true;
            }
        }
        if (!swapped) {
            break;
        }
    }

    return result;
}

void main() {
    IO.println(Arrays.toString(bubbleSort(new int[] {64, 25, 12, 22, 11})));
    IO.println(Arrays.toString(bubbleSort(new int[] {1, 2, 3, 4, 5})));
}

// From Groundwork, chapter 11 (ch11-searching-and-sorting), box 6.
// This example is from Groundwork, licensed CC BY-NC-SA 4.0.
// Run with: java ch11_06.java
