# Bubble Sort Algorithm

The simplest sorting algorithm. It gets it’s name from the fact that the smaller or bigger numbers seem to “bubble” up. Works on the logic of comparing adjacent elements and swapping them if they are in the wrong order.

Logic:
1. So we run two loops, the first one (let’s call it loop i) starting from the end of the array and the second one (let’s call it loop j) starting from the beginning all the way to i-1.
2. Compare each element (array[j]) with it’s next element (array[j+1])
3. For ascending order arrangement: if A[j]>A[j+1] swap the two numbers
4. For ascending order arrangement: if A[j]<A[j+1] swap the two numbers

Code:

``````
public class bubble_sort {
public static void main (String [] args){
int [] array= {4,1,5,9,0,6,3,7,8,2};
int length= array.length;

for(int i=length-1; i>=0; i--){
for(int j=0; j<=i-1; j++){
if(array[j]>array[j+1]){
int temp= array[j];
array[j]= array[j+1];
array[j+1]= temp;
}
}
}

for(int i=0; i<length; i++){
System.out.println(array[i]);
}

}

}
``````

HAPPY LEARNING!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.