Useful Java Code Snippets 10 - Bubble Sort in Java

Hello everyone, today's java code snippet is about bubble sorting. Bubble sort is the easiest way to sort a collection of numbers. It works by sequentially going through the array and comparing two consecutive values at a time, swapping them if necessary. Then, the process is repeated until no swaps are required.

The code generates 100 random double values and stores them in an array. Then by using the Sort class, which is given below, the array is sorted and printed to the screen;

* Author : Berk Soysal

 public class Sort {
  //instance variables
  private double array[];
  private double temp;
  //constructor method
  public Sort(double array[]){
    this.array = array;
  //sortArray method sorts and returns a double[]
  public double[] sortArray(){
    double temp;
    for(int i=0; i < array.length-1; i++){
      for(int j=1; j < array.length-i; j++){
        if(array[j-1] > array[j]){
          array[j-1] = array[j];
          array[j] = temp;
    return array;

* Author : Berk Soysal

public class Main {
  public static void main(String[] args) {
    //Define the arrays
    double c[] = new double[100];
    double cnew[] = new double[c.length];
    //Generate the random values
    for (int i=0;i<c.length;i++)
      c[i] = Math.random();
    //Sort the random array c
    cnew = (new Sort(c)).sortArray();
    //Print the sorted array cnew
    for (int i=0;i<cnew.length;i++)

 The output;



Please leave a comment if you have any comments, questions or suggestions. Thanks!

Continue Reading Useful Java Code Snippets 11 - The Stack Class in Java


Software Developer, Codemio Admin

Disqus Comments Loading..