Bubble sort program in java

Bubble sorting  as known as sink sorting  is an east and simple sorting algorithm. This sorting algorithm is correlation based algorithm in which each pair of adjacent element is compared and the elements are swapped if they are not the right sequence. This algorithm is not good for the large data sets and not efficient than the quick and heap sorting.

There are two .java classes for the Bubble sorting Algorithm:

  1. Runner class.
  2. Sort Class.

Code is successfully compiled on the Eclipse compiler.

Runner Class:

package bubble_sort;

public class Runner {
public static void main(String args[])
{
int maxSize = 100;
Sort sort = new Sort(maxSize);

sort.insert(77);
sort.insert(99);
sort.insert(44);
sort.insert(55);
sort.insert(22);
sort.insert(88);
sort.insert(11);
sort.insert(00);
sort.insert(66);
sort.insert(33);

// sort.display();
sort.BubbleSort();

// sort.display();
}
}

Sort Class:

package bubble_sort;

public class Sort {

private long[] a;
private int nElems;

public Sort(int max)
{
a = new long[max];
nElems = 0;
}
public void insert(long value)
{
a[nElems] = value;
nElems++;
}
public void display()
{
for(int i=0; i<nElems; i++)
{
System.out.print(a[i] + ” “);
}
System.out.println(); }

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])
{
swap(in, in+1);
for(int i=0; i<nElems ; i++)
{
System.out.print(a[i]+”.”);
}
System.out.println();
}
}
}
}
public void swap(int one, int two)
{
long temp = a[one];

a[one]= a[two];
a[two] = temp;
}
}

Comment if you have any confusion or query thanks !!!

One Comment

Add a Comment

Your email address will not be published. Required fields are marked *