java tutorial - How to implement Bubble Sort Algorithm in java - java programming - learn java - java basics - java for beginners

Learn Java - Java tutorial - bubble sort in Java - Java examples - Java programs
Bubble Sort Algorithm
- Bubble sort is an easy sorting algorithm and continued steps completed the list to be sorted, compares each pair of nearby objects and swaps them if they are in the incorrect order.
- The permission complete the list is continued till no swaps are compulsory, which shows that the list is sorted.
- The algorithm, which is a comparison sort, is called for the way smaller or higher elements "bubble" to the top of the list.
- Although the algorithm is simple.
sample code:
public class BubbleSort {
public static void main(String[] args)
{
int[] c={20,65,12,25,98,45,38};
System.out.print("Before Bubble sort \n");
printArray(c);
bubblesort(c);
System.out.print("\nAfter Bubble sort \n");
printArray(c);
}
public static void printArray(int[] v)
{
for(int i=0 ; i< v.length; i++)
{
System.out.print(v[i]+" ");
}
}
public static void bubblesort(int[] v)
{
int temp = 0;
for(int i =v.length;i>=0; i--)
{
for(int j=0;j< i-1;j++)
{
if(v[j]>v[j+1])
{
temp = v[j+1];
v[j+1] = v[j];
v[j] = temp;
}
}
}
}
}
Output:
Before Bubble sort
20 65 12 25 98 45 38
After Bubble sort
12 20 25 38 45 65 98