Bubble Sort

Bubble sort is a simple algorithm used to sort an unsorted array by repeatedly swapping adjacent elements if they are in the wrong order. It is called bubble sort because smaller elements "bubble" to the top of the array as we iterate through it.
How Bubble Sort Works
Bubble sort works by iterating through an array and comparing adjacent elements. If the two adjacent elements are in the wrong order, we swap them. We repeat this process until the array is fully sorted.
Here is an overview of how the bubble sort algorithm works:
Start at the beginning of the array
Compare the first two elements
If the first element is greater than the second element, swap them
Move to the next pair of elements and repeat step .
Repeat the previous step until the end of the array is reached
If any swaps were made in the previous step, repeat the entire process again
Stop the algorithm when no more swaps are being done
Example Implementation in Java
Here's an example implementation of bubble sort in Java:
public static void bubbleSort(int[] arr) {
for(int i=0; i<arr.length-1; i++){
for(j=1; j<arr.length-i; j++){
if(arr[j]<arr[j-1]){
// just swap them
int temp=arr[j];
arr[j]= arr[j-1];
arr[j-1]=temp;
}
}
}
}
The bubbleSort function takes in an array of integers and iterates through it, comparing adjacent elements and swapping them if they are in the wrong order. We continue iterating through the array until it is fully sorted.
In every pass the largest element is coming at the last index . Hence, there is no point of comparing any element with the last one that's why the loop of j is continuing till arr.length-i index.
Conclusion
Bubble sort is a basic sorting algorithm that is easy to implement but has a time complexity of O(n^2) which makes it inefficient for large arrays. Despite its simplicity, bubble sort is still used in certain situations where the array is small or nearly sorted. In this post, I have provided an example implementation of bubble sort in Java.
About the author
I am currently an undergraduate in Computer Science and Engineering . I am currently working on my skills in java language and I also having knowledge of C language. Looking forward to improve my skills in android development and making some interesting projects .
Comments
Join the discussionNo comments yet. Be the first to comment.




