Sort an array with bubble sort

Description: Sort {64, 34, 25, 12, 22, 11, 90} in ascending order without using Arrays.sort(). Then check your answer with Arrays.sort().

Hint:

  • Compare each pair of neighbours and swap them if they are in the wrong order. Repeat.

Solution

import java.util.Arrays;

public class Main {
    static void bubbleSort(int[] a) {
        for (int i = 0; i < a.length - 1; i++) {
            boolean swapped = false;
            for (int j = 0; j < a.length - 1 - i; j++) {
                if (a[j] > a[j + 1]) {
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                    swapped = true;
                }
            }
            if (!swapped) break;           // already sorted
        }
    }

    public static void main(String[] args) {
        int[] data = {64, 34, 25, 12, 22, 11, 90};
        int[] check = data.clone();

        bubbleSort(data);
        Arrays.sort(check);
        System.out.println(Arrays.toString(data));
        System.out.println(Arrays.equals(data, check));
    }
}
Output

[11, 12, 22, 25, 34, 64, 90]
true

How it works

  • After each round of the outer loop, the biggest remaining value goes to its place at the end.
  • If a full round makes no swap, the array is sorted and we stop.
  • Bubble sort is good to learn, but slow (O(n squared)). Real code uses Arrays.sort().

Read Java Arrays.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.