Guest User

Untitled

a guest
May 26th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.32 KB | None | 0 0
  1. public class ArrayBub {
  2.     private long[] a; //ref to array a
  3.     private int nElems; //number of data items
  4.    
  5. ///////////////////////////////////////////////
  6.  
  7.     public ArrayBub( int max ) { //constructor
  8.         a = new long[max]; //create the array
  9.         nElems = 0; //no item yet
  10.     }
  11.  
  12. //---------------------------------------------
  13.  
  14.     public void insert( long value ) { //put element into array
  15.         a[nElems] =  value; //insert one item
  16.         nElems++; //increase arrat size
  17.     }
  18.    
  19. //---------------------------------------------
  20.  
  21.     public void display() { //display array contents
  22.         for ( int j = 0; j < nElems; j++ ) { //for each element
  23.             System.out.print( a[j] + " " ); //display it
  24.         }
  25.         System.out.println( "" );
  26.     }
  27.    
  28. //---------------------------------------------
  29.  
  30.     public void bubbleSort() {
  31.         int in; //from left to right
  32.         int out; //from right to left
  33.        
  34.         for ( out = nElems-1; out > 0; out-- ) { //outer loop(right to left) textbook is wrong about this line, "out > 0" is correct rather "out > 1"
  35.             for ( in = 0; in < out; in++ ) { //inner loop(left to right)
  36.                 if ( a[in] > a[in+1] ) { //out of order?
  37.                     swap( in, in+1 ); //swap them
  38.                 }
  39.             }
  40.         }
  41.     }
  42.    
  43. //---------------------------------------------
  44.  
  45.     public void swap( int one, int two ) {
  46.         long temp = a[one];
  47.         a[one] = a[two];
  48.         a[two] = temp;
  49.     }
  50. }
Add Comment
Please, Sign In to add comment