Java Data Structure How to - Implement a Bubble Sort








Question

We would like to know how to implement a Bubble Sort.

Answer

public class MainClass {
  public static void main(String[] args) {
    int[] intArray = new int[] { 2, 6, 3, 8, 4, 9, 1 };
//w  w w .j a v a2 s .c  o  m
    for (int i : intArray) {
      System.out.print(i);
    }
    System.out.println();
    bubbleSort(intArray);

    for (int i : intArray) {
      System.out.print(i);
    }

  }

  public static void bubbleSort(int[] intArray) {
    int out, in;
    for (out = intArray.length - 1; out > 0; out--) {
      for (in = 0; in < out; in++) {
        if (intArray[in] > intArray[in + 1]) {
          swap(intArray, in, in + 1);
        }
      }
    }
  }

  private static void swap(int[] intArray, int one, int two) {
    int temp = intArray[one];
    intArray[one] = intArray[two];
    intArray[two] = temp;
  }
}   

The code above generates the following result.