Program 9.7: Bubble Sort

A bubble sort starts at the top of the array. Each component is compared to the next component. If it is greater than the next component component, then swap the two. Pass through the array as many times as necessary to sort it. The smallest value bubbles up to the top of the array while the largest value sinks to the bottom. (You could equally well call it a sink sort, but then nobody would know what you were talking about.) Program 9.7 demonstrates this by filling an array with ten random numbers and then sorting them.

import java.util.Random;

class BubbleSort {

  public static void main(String args[]) {
  
   int[] n;
   n = new int[10];
   Random myRand = new Random();
   
   // initialize the array
   for (int i = 0; i < 10; i++) {
     n[i] = myRand.nextInt();
   }
   
   // print the array's initial order
   System.out.println("Before sorting:"); 
   for (int i = 0; i < 10; i++) {
     System.out.println("n["+i+"] = " + n[i]);
   }
   
   boolean sorted = false;
   // sort the array
   while (!sorted) {
     sorted = true;
     for (int i=0; i < 9; i++) {
       if (n[i] > n[i+1]) {
         int temp = n[i];
         n[i] = n[i+1];
         n[i+1] = temp;
         sorted = false;
       }   
     }
   }

  // print the sorted array
  System.out.println();
  System.out.println("After sorting:");  
    for (int i = 0; i < 10; i++) {
      System.out.println("n["+i+"] = " + n[i]);
    }
  
  }

}
This program sorts the array in ascending order, smallest component first. It would be easy to change it to sort in descending order.


Copyright 1996 Elliotte Rusty Harold
elharo@sunsite.unc.edu
This Chapter
Examples
Home