Monday, July 1, 2013

BubbleSort in JAVA

ArrayBub.Java Class

public class ArrayBub {

private long[] a;
private int nElems;

public ArrayBub(int max){
nElems = 0;
a = new long[max];
}

public void insert(long value){
a[nElems++]= value;
}

public void display(){
for(int i=0;i<nElems;i++){
System.out.print(a[i] + " ");
}
}

public void bubbleSort(){
int out, in;

for(out= nElems -1; out > 1; out--){
for(in=0;in<out;in++){
if(a[in] > a[in+1]){
long temp = a[in];
a[in] = a[in+1];
a[in+1] = temp;
}
//swap(in,in+1);
}
}

}

private void swap(int one, int two){
long temp = a[one];
a[one] = a[two];
a[two] = temp;
}

}

----------------------------------------------------------------------------------------------------------------------------------
BubbleSortApp.java class

public class BubbleSortApp {

public static void main(String[] args) {

int maxSize = 100;
ArrayBub  bub;
bub = new ArrayBub(maxSize);

bub.insert(77);
bub.insert(43);
bub.insert(99); // insert 10 items
bub.insert(44);
bub.insert(55);
bub.insert(22);
bub.insert(88);
bub.insert(11);
bub.insert(00);
bub.insert(66);
bub.insert(33);
bub.display();

bub.bubbleSort();
System.out.println("");
bub.display();
}

}