1. Bubble Sort
Learn How bubble sort work, it’s usage and best
practices By: Gaurav Kumar
2. High-Level Thoughts
Runtime Complexity:
* Best Case : O(n)
* Average Case : O(n^2)
* Worst Case : O(n^2)
Memory Space: O(1),No Additional Space required
Stability: Stable, does not change the relative order of elements with equal keys
Adaptive: O(n) when nearly sorted
3. Idea for Usage
This Sorting Algorithm is suitable when we have small data sets because
bubble sort is very slow for large data sets as running complexity is O(n^2).
Bubble sort is stable sorting and takes no extra space so these are advantages
of this algorithm.
4. Bubble Sort Concept
In the bubble sort, as elements are sorted they gradually "bubble" (or rise) to
their proper location in the array, like bubbles rising in a glass of soda. Instead
of searching an array as a whole, the bubble sort works by comparing adjacent
pairs of objects in the array. If the objects are not in the correct ordered, they
are swapped so that the largest of the two moves up. This process continues
until the largest of the objects, eventually "bubbles" up to the highest position in
the array. After this occurs, the search for the next largest object begins. The
swapping continues until the whole array is in the correct order.
5. Code Snippet private static int[] bubbleSort(int[] arr)
{
int alen = arr.length;
for (int i = 0; i < alen - 1; i++)
{
for (int j = 0; j < alen - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
6. How to Improve above code snippet?
As you see, there are two for loop are running and having running time
complexity O(n^2).But suppose input array is already sorted that time also
above code run O(n^2). Just think for a minute !
We have to write some logic in above code so that we could aware that input
array is already sorted. In bubble sort we are comparing each element with the
adjacent element if they are out of order then we are swapping. Then if our
input array is already sorted then there will be no swapping of elements. So we
could maintain a flag, if in first pass of for loop there is no swapping of element
then make that flag true and break the for loop for further operation.