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;

Sort.java

/**
* 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]){
          temp=array[j-1];
          array[j-1] = array[j];
          array[j] = temp;
        }
      }
    }
    return array;
  }
}


Main.java

/**
* 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++)
      System.out.println(cnew[i]);
  }
}

 The output;

0.0026657725763379325
0.005961409381626148
0.012323789591339174
.

.
0.954999597312328
0.9621105985611431
0.9686866385530238
0.9698970428605861
0.9757546260066293


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

Author:

Software Developer, Codemio Admin

Disqus Comments Loading..