Bubble Sort
- Categories Java, Arrays in Java
What is bubble sort?
Bubble Sort algorithm is also called as sinking sort or comparison sort.
The algorithm is named so as the smaller values which are lighter gradually bubble up to the top of the list. And larger values which are heavier gradually sink to the bottom of the list
To continue learning, please watch our animated video on bubble sort: https://youtu.be/MbzGRQeY5mc
Pseudo code:
START
Take an array or list of size n in list
FOR i = 0 TO i < (n-1) // Loop for the pass
FOR j = 0 TO j < (n – 1 – pass ) // Loop for the comparison
IF list[j] > list[j+1]
swap list[], list[j+1]
END IF
END FOR
END FOR
END
JAVA code:
void bubble(int [] list,int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-1-i; j++)
if (list[j] > list[j+1]) {
int temp = list[j]; // swap j and j+1
list[j] = list[j+1];
list[j+1] = temp;
}
}
}
}