Tuesday, June 7, 2016

Simple Bubble Sorting in Java

Simple Sorting:

Sorting is very important thing in computer science because it is just a preliminary step to search sorted data.A binary search is much faster than a linear search because sorting is so important and potentially so time consuming .basically sorting can be applied to any thing such as number,string etc.

There are few Simple Sorting Algorithms available which will see below:

  1. Bubble Sort 
  2. Selection Sort
  3. Insertion Sort


  • Bubble Sort: here are the rules you will follow while bubble sort
  1. Compare two players
  2. if the one on the left is taller ,swap them.
  3. Move one position right.
Efficiency of the Bubble Sort:

 Both swap and comparisons are proportional  to N^2 .
Bubble sort runs in O(N^2)  .

Sample Code Workshop:


/**
 *
 */

/**
 * @author Abhinaw.Tripathi
 *
 */
class ArrayBub
{
  private long[] a;
  private int nElems;

  public ArrayBub(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.println(a[i] + " ");
 System.out.println(" ");
 }
  }

  public void bubbleSort()
  {
 int out,in;
 for(out=nElems;out>1;out--)
 for(in=0;in<out;in++)
 if(a[in] > a[in+1])
 swap(in,in+1);
  }

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

}

public class BubbleSortTest {
/**
*
*/
public BubbleSortTest() {
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

int maxsize=100;
ArrayBub arr =new ArrayBub(maxsize);
arr.insert(77);
arr.insert(99);
arr.insert(44);
arr.insert(55);
arr.display(); // before sort

arr.bubbleSort();
arr.display();  //after sort display again
}

}

No comments: