Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ArrayBub {
- private long[] a; //ref to array a
- private int nElems; //number of data items
- ///////////////////////////////////////////////
- public ArrayBub( int max ) { //constructor
- a = new long[max]; //create the array
- nElems = 0; //no item yet
- }
- //---------------------------------------------
- public void insert( long value ) { //put element into array
- a[nElems] = value; //insert one item
- nElems++; //increase arrat size
- }
- //---------------------------------------------
- public void display() { //display array contents
- for ( int j = 0; j < nElems; j++ ) { //for each element
- System.out.print( a[j] + " " ); //display it
- }
- System.out.println( "" );
- }
- //---------------------------------------------
- public void bubbleSort() {
- int in; //from left to right
- int out; //from right to left
- 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"
- for ( in = 0; in < out; in++ ) { //inner loop(left to right)
- if ( a[in] > a[in+1] ) { //out of order?
- swap( in, in+1 ); //swap them
- }
- }
- }
- }
- //---------------------------------------------
- public void swap( int one, int two ) {
- long temp = a[one];
- a[one] = a[two];
- a[two] = temp;
- }
- }
Add Comment
Please, Sign In to add comment