There are different sorting algorithms are available like selection sort, insertion sort etc. In this article we learn about one of them sorting algorithm, working of this sorting algorithm and example of this sorting algorithm. Bubble sort algorithm is the simplest sorting algorithm as compare to other sorting algorithms.

In the bubble sorting algorithm, array is traversed from first element to last element. In this sorting, compare the current element with the next element. If current element is greater than the next element, then swap the elements.

Algorithm:

We assume list or an array of n elements. We further assume that swap function swaps the values of the given array elements.

``````begin BubbleSort(list)
for all elements of list
if list[i] > list[i+1]
swap(list[i], list[i+1])
end if
end for
return list
end BubbleSort``````

#### Program: Bubble sort program in java

In the following program we pass the integer array of numbers for sorting. Before sorting array int arr looks like {3,60,35,2,45,320,5} and after performing bubble sorting array of integers looks like {2 ,3 ,5 ,35 ,45 ,60 ,320}

``````public class BubbleSortExample
{
static void bubbleSort(int[] arr)
{
int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++)
{
for(int j=1; j < (n-i); j++)
{
if(arr[j-1] > arr[j])
{
//swap elements
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
public static void main(String[] args)
{
int arr[] = {3,60,35,2,45,320,5};
System.out.println("Array Before for(int i=0; i < arr.length; i++)
{
System.out.print(arr[i] + " }
System.out.println();
bubbleSort(arr);//sorting array elements System.out.println("Array After for(int i=0; i < arr.length; i++)
{
System.out.print(arr[i] + " }
}
}``````

Output:

Array Before Sorting
3 60 35 2 45 320 5
Array After Sorting
2 3 5 35 45 60 320

In the above programs output we see that the values are sorted. Here in this article we sort the arrays by ascending order we can also try this sorting for descending order.i.e increasing order or decreasing order.

Other than the bubble sorting we write the articles for other sorting algorithms which are available in programming like Insertion sort, merge sort. If you want to learn about them then see below articles. Learn about merge sort see this article Merge Sort. If you want to learn Insertion sort, quick sort, selection sort then see this article Insertion Sort, Quick sort, Selection sort.

I hope you would like this article of sorting. If you face any difficulty or you are having any query then comment me I will definitely try to respond you…