Sorting of Array Elements using Java Sorting is the process of arranging given set of elements in either ascending order or descending order. The searching process is easily facilitated when the data elements are in sorted order.

Searching for a data element, is simple and fast in a sorted array. Binary Search makes use of sorted array. There are various ways of sorting an array. We will see Bubble sort and Selection sort in this article.

Bubble Sort

In Bubble Sort, adjacent elements are compared, in order to arrange data elements in descending order. If the adjacent element is bigger, than they are interchanged i.e Swapping is done.

It happens for the entire set of data elements. The process is repeated till all the data elements are sorted.

The process is same for sorting the elements in ascending order, and swapping will be done when the adjacent element is smaller.

Let us see the Video explanation for Bubble sort.

Program for Bubble Sort in Java

class BubbleSort
{
	public void sort(int a[]) //passing argument 
	{
		int l = a.length;
		int t; //Temporary variable that helps in swapping
		for(int i=0;i<l-1;i++)
		{
			for(int j=0;j<l-i-1;j++)
			{
				if(a[j]<a[j+1])
				{
					t = a[j];
					a[j] = a[j+1];    //Swapping Logic
					a[j+1] = t;
				}
			}
		}
		for(int i=0;i<l;i++)
			System.out.println(a[i]);
	}
	public static void main(String args[]) {
		BubbleSort b=new BubbleSort();
		int a[]= new int[]{5,6,1,8,9};
		b.sort(a);
	}
}
OUTPUT:
9 
8 
6 
5 
1 

 

Selection Sort

In Selection Sort, the maximum or minimum element is determined and it is swapped with the first element, the same process is repeated for second element, third element and so on.

Let us see the Video explanation for Selection Sort

Program for Selection Sort in Java

class SelectionSort
{
	static void sort(int a[])
	{
		int l = a.length;
		int m , p;
		for(int i=0;i<l;i++)
		{
			m = a[i];   //assuming the maximum element is at a[i]
			p = i;
			for(int j=i+1;j<l;j++)
			{
				if(a[j]>m)
				{	
					m = a[j];  //determining the maximum element
					p = j;
				}
			}
			a[p] = a[i];
			a[i] = m;
		}
		for(int i=0;i<l;i++)
			System.out.print(a[i] + " ");
	}
	public static void main(String args[]) {
		BubbleSort b=new BubbleSort();
		int a[]= new int[]{5,3,6,0,8,9,6,7,1};
		b.sort(a);
	}
}
OUTPUT:
9 8 7 6 6 5 3 1 0